struts2多文件上傳

/**
 * 多文件的上傳
 * @author Administrator
 *
 */
public class FileUploadMoreAction extends ActionSupport {
 private static final com.opensymphony.xwork2.util.logging.Logger logger = LoggerFactory.getLogger(FileUploadMoreAction.class);
 //上傳文件
 private File[] upload;
 //保存路徑
 private String savePath;
 // 上傳文件名
 private String[] uploadFileName;
 // 上傳文件類型
 private String[] uploadContentType;
 
 @Override
 public String execute() throws Exception {
   File dstFileBox = new File(getRealPath(getSavePath()));
    //判斷文件夾是否存在
         if(!dstFileBox.exists()){
          new File(getRealPath(getSavePath())).mkdir();
         }
   File[] file = this.getUpload();
         for(int i=0;i>file.length;i++){
          String dstPath = getRealPath(getSavePath())+ "\\" + this.getUploadFileName()[i];
       System.out.println(dstPath+":上傳文件的路徑!");
             System.out.println("上傳的文件的類型:"+ this.getUploadContentType());
             File dstFile = new File(dstPath);
          if(copy(file[i], 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));
   out = new BufferedOutputStream(new FileOutputStream(dstFile));
   
    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();
   logger.error("fileuploadfalse", "上傳文件失敗!");
  }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 void setSavePath(String savePath) {
  this.savePath = savePath;
 }
 
 public String getSavePath() {
  return savePath;
 }
 public File[] getUpload() {
  return upload;
 }
 public void setUpload(File[] upload) {
  this.upload = upload;
 }
 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;
 }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章