⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileuploadaction.java

📁 struts2图片上传源码
💻 JAVA
字号:
package org.yeeda.struts;

import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {
	private static final long serialVersionUID = 572146812454l;
	private static final int BUFFER_SIZE = 16 * 1024;
	private static Connection conn = null;
	private static PreparedStatement pstmt = null;

	private File myFile;//上传文件域对象
	private String myFileFileName;
	private String imageFileName;
	private String caption;
	private String savePath;
	
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	private String getSavePath() throws Exception
	 {
	         return ServletActionContext.getRequest().getRealPath(savePath);
	     }

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	
	public String getCaption() {
		return caption;
	}

	public void setCaption(String caption) {
		this.caption = caption;
	}

	public String getMyFileFileName() {
		return myFileFileName;
	}

	public void setMyFileFileName(String myFileFileName) {
		this.myFileFileName = myFileFileName;
	}

	public File getMyFile() {
		return myFile;
	}
	
	public String getImageFileName() {
		return imageFileName;
	}


	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}
	
	private static boolean connectSQLServer() {
		String url = "";
		String username = "sa";
		String password = "sa";

		// 加载驱动程序以连接数据库
		try {
			// 添加类库驱动包
			Class.forName("net.sourceforge.jtds.jdbc.Driver");
			url = "jdbc:jtds:sqlserver://localhost:1433/master";
			conn = DriverManager.getConnection(url, username, password);
			//stmt = conn.createStatement();
		}
		// 捕获加载驱动程序异常
		catch (ClassNotFoundException cnfex) {
			System.err.println("装载JDBC驱动程序失败。");
			cnfex.printStackTrace();
			return false;
		}
		// 捕获连接数据库异常
		catch (SQLException sqlex) {
			System.err.println("无法连接数据库");
			sqlex.printStackTrace();
			// System.exit(1); // terminate program
			return false;
		}
		return true;
	}
	
	
	private static void dealPic(File bigFile,File smallFile){
		  try {
			  	AffineTransform transform = new AffineTransform();
	            BufferedImage bis = ImageIO.read(bigFile);

	            int w = bis.getWidth();
	            int h = bis.getHeight();
	            double scale = (double)w/h;
	            if(w>h){
	            	int nw = 120;
	            	int nh = (nw * h) / w;
	            	double sx = (double)nw / w;
		            double sy = (double)nh / h;

		            transform.setToScale(sx,sy);

		            AffineTransformOp ato = new AffineTransformOp(transform, null);
		            BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
		            ato.filter(bis,bid);
		            ImageIO.write(bid, "jpeg", smallFile);
	            }
	            else{
	            	int nh = 120;
	            	int nw = (nh * w) / h;
	            	double sx = (double)nw / w;
		            double sy = (double)nh / h;

		            transform.setToScale(sx,sy);

		            AffineTransformOp ato = new AffineTransformOp(transform, null);
		            BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
		            ato.filter(bis,bid);
		            ImageIO.write(bid, "jpeg", smallFile);
	            }     
	      }
		  catch(Exception e) {
			  e.printStackTrace();
		  }     
	}
	
    private static void copy(File src, File dst) 
    {
        InputStream in = null;
        OutputStream out = null;
        try 
        {
            in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
            out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);
            byte[] buffer = new byte[BUFFER_SIZE];
            int len = 0;
            while ((len = in.read(buffer)) > 0) 
            {
                out.write(buffer, 0, len);
            }
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        } 
        finally
        {
            if (null != in) 
            {
                try 
                {
                    in.close();
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
            if (null != out) 
            {
                try 
                {
                    out.close();
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
        }
    }
 
	
	

	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(0, pos)+"_s"+fileName.substring(pos);
	}

	@Override
	public String execute(){
			if(myFileFileName != null){
				String sql;
				sql = "insert into img(filepath) values(?)";
				imageFileName = getExtention(myFileFileName);
				String filePath;
				try {
					filePath = getSavePath()+"/"+myFileFileName;//上传的文件的路径
					String smallFilePath =getSavePath()+"/"+imageFileName;//缩略后的文件的路径
					if(connectSQLServer() == true){
						try {
			        		conn.setAutoCommit(false);
			        		pstmt = conn.prepareStatement(sql); 
			        		pstmt.setString(1,filePath);   
			        		pstmt.executeUpdate();
			                conn.commit();
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							try {
								conn.rollback();
							} catch (SQLException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
						finally{
							if(pstmt != null){
								try {
									pstmt.close();
								} catch (SQLException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							if(conn != null){
							try {
								conn.close();
							} catch (SQLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					File a = new File(filePath);
					File b = new File(smallFilePath);
			        copy(this.getMyFile(), a);
			        dealPic(this.getMyFile(), b);
					}
				}catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return SUCCESS;
			}
			else{
				return ERROR;
			}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -