標籤:
一、藉助Struts2架構
1.環境搭建
1.1 導包:conmmons-fileupload-1.2.1.jar conmmons-io-1.4.jar 以及其他架構的jar包
2.頁面:略
3.檔案上傳:
3.1 設計一個檔案上傳工具類:FileUploadUtils
1 public class FileUploadUtils{ 2 3 //檔案要上傳到的路徑,可配置 4 @Resource 5 private String filePath; 6 7 private String createNewFilePath(String fileName){ 8 9 //原始路徑為配置的filePath10 String basePath=filePath;11 //子路徑為格式化的/年/月/日形式12 SimpleDateFormat sdf=new SimpleDateFormat("/yyyy/MM/dd");13 String subPath=sdf.format(new Date());14 15 //如果沒有目錄檔案夾就建立16 File dir=new File(basePath+subPath);17 if(!dir.exists()){18 //遞迴地建立目錄檔案夾19 dir.mkdirs();20 }21 22 //新檔案名稱為UUID+副檔名23 String newFileName=UUID.randomUUID().toString()//24 +fileName.substring(fileName.lastIndexOf("."));25 //這是新產生的檔案路徑26 String newFilePath=basePath+subPath+newFileName;27 28 return newFilePath;29 }30 31 public String saveUploadFile(File uploadFile,String fileName){32 //新檔案路徑33 String newFilePath=createNewFilePath(filePath,fileName);34 try{35 //擷取檔案輸入輸出資料流36 InputStream in=new FileInputStream(uploadFile);37 OutputStream out=new FileOutputStream(newFilePath);38 39 //往目標路徑檔案中寫位元組流40 byte[] buff=new byte[1024];41 int len=0;42 while((len=in.read(buff))!=-1){43 out.write(buff,0,len);44 }45 46 47 }catch(Exception e){48 49 throw new RuntimeException();50 }finally{51 try{52 in.close();53 }catch(Exception e){54 throw new RuntimeException();55 }finally{56 try{57 out.close();58 }catch(Exception e){59 throw new RuntimeException();60 }61 62 }63 64 }65 66 return newFilePath;67 }68 }69
4.檔案下載:Struts2中封裝之後就很簡單
1 public class XXXAction extends ActionSupport implements ModelDriven{ 2 3 //供下砸用的輸入資料流 4 private InputStream inputStream; 5 //需寫setter,getter; 6 7 //模型驅動,簡化傳參,替代了Strtus1的ActionForm 8 private XXX model=new XXX(); 9 public XXX getModel(){10 returm model;11 }12 13 public String download(){14 XXX xxx=xxxService.getById(model.getId());15 inputStream=new FileInputStream(new File(xxx.getPath()));16 17 //解決中文亂碼問題18 String fileName=URLEncoder.encode(xxx.getFileName(),"utf-8");19 ActionContext.getContext.put("fileName",fileName);20 }21 }
剩下的就是struts.xml的配置了
二、用純Servlet(續)
Java Web開發中的檔案上傳與下載