struts2文件上傳

/**
 * 單文件的上傳
 * @author Administrator
 *
 */
public class FileUploadAction extends ActionSupport {
 private static final com.opensymphony.xwork2.util.logging.Logger logger = LoggerFactory.getLogger(FileUploadAction.class);
 //上傳文件
 private File upload;
 //保存路徑
 private String savePath;
 // 上傳文件名
 private String uploadFileName;
 // 上傳文件類型
 private String uploadContentType;
 
 @Override
 public String execute() throws Exception {
  
   String dstPath = getRealPath(getSavePath())+ "\\" + this.getUploadFileName();
   System.out.println(getRealPath(getSavePath())+"文件路徑");  
         System.out.println("上傳的文件的類型:"+ this.getUploadContentType());            
         File dstFileBox = new File(getRealPath(getSavePath()));
         //判斷文件夾是否存在
         if(!dstFileBox.exists()){
          new File(getRealPath(getSavePath())).mkdir();
         }
         File dstFile = new File(dstPath);
         //返回true表示上傳成功,返回false表示上傳失敗
        if(copy(this.getUpload(), dstFile)){
         return SUCCESS;
        }
        return SUCCESS;
 }
 
 public static Boolean copy(File file,File dstFile) throws Exception {
        boolean restlt = false;  
  InputStream in = null;
  OutputStream out = null;
  try {
   in = new BufferedInputStream(new FileInputStream(file));
   System.out.println("讀文件");
   out = new BufferedOutputStream(new FileOutputStream(dstFile));
   System.out.println("寫文件");
    byte[] buffer = new byte[5*1024];  
    int len = 0;
   if((len = in.read(buffer))>0){
    out.write(buffer,0,len);
   }
   restlt = true;
  } catch (Exception e) {
   e.printStackTrace();
  }finally{
   if(null != in){
    try {
     in.close();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
   if(null != out){
    try {
     out.close();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }
  return restlt;
 }
 
 //------------------------------------------------------------------------------
   private String getRealPath(String path) {
  
  return ServletActionContext.getServletContext().getRealPath("path");
 }
 public File getUpload() {
  return upload;
 }
 public void setUpload(File upload) {
  this.upload = upload;
 }
 public void setSavePath(String savePath) {
  this.savePath = savePath;
 }
 
 public String getSavePath() {
  return savePath;
 }
 public String getUploadFileName() {
  return uploadFileName;
 }
 public void setUploadFileName(String uploadFileName) {
  this.uploadFileName = uploadFileName;
 }
 public String getUploadContentType() {
  return uploadContentType;
 }
 public void setUploadContentType(String uploadContentType) {
  this.uploadContentType = uploadContentType;
 }
 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章