struts的檔案上傳與下載
阿新 • • 發佈:2018-11-09
struts的檔案上傳與下載後臺程式碼
package interceptor; import java.io.File; import java.io.IOException;import org.apache.commons.io.FileUtils; import web.BaseAction; /** * 檔案上傳的三種方案: * 1.將上傳的檔案以二進位制的形式存放到資料庫 oa系統 activiti工作框架 * 2.將檔案上傳到檔案伺服器(硬碟足夠大,cpu轉速快)中 * 3.將檔案上傳到tomcat所在的普通web伺服器 * 真實路徑與虛擬路徑的概念 * 1.真實路徑是指在自己電腦上能夠看到的路徑 * 2.虛擬在自己電腦看不到的路徑 * @author ASUS */ public class UpladAction extends BaseAction { private File file;//變數名指的是jsp的name屬性,就是你要上傳的檔案 private String fileContenType;//檔案型別 private String fileFileName;//檔名 private String servletDri="/upload";//你所指定得檔案存放路徑 //檔案上傳 public String upload() { System.out.println(fileContenType); System.out.println(fileFileName); // 指的是Linux下的檔案的所在位置 String realPath=getRealPath(servletDri+"/"+fileFileName); System.out.println(realPath); // 引數1:指的是本地圖片檔案,,引數2:在伺服器生成的檔案 try { FileUtils.copyFile(file, new File(realPath));//表示從本地圖片檔案複製到伺服器生成的檔案 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return SUCCESS; } /** * 獲取Linux下的檔案的所在位置 * @param path * @return */ private String getRealPath(String path) { // TODO Auto-generated method stub return application.getRealPath(path); } public String openAs() { String type="image/jpeg";//你要開啟得圖片型別 String name="333.jpg";//你要開啟得檔名 response.setContentType(type); response.setHeader("Content-Disposition","filename=" + name); /** * 將遠端的圖片輸出到本地 * 資料來源inputstream:遠端new File(realPath) * 目的:輸出到本地得jsp:response.getOutputStream() */ 指的是Linux下的檔案的所在位置 String realPath=getRealPath(servletDri+"/"+name); try { FileUtils.copyFile(new File(realPath), response.getOutputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public String download() { String type="image/jpeg"; String name="333.jpg"; response.setContentType(type); //檔案下載中setHeader必須有attachment response.setHeader("Content-Disposition","attachment;filename=" + name); /** * 將遠端的圖片輸出到本地 * 資料來源inputstream:遠端new File(realPath) * 目的:輸出到本地得jsp:response.getOutputStream() */ // 指的是Linux下的檔案的所在位置 String realPath=getRealPath(servletDri+"/"+name); try { FileUtils.copyFile(new File(realPath), response.getOutputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileContenType() { return fileContenType; } public void setFileContenType(String fileContenType) { this.fileContenType = fileContenType; } public String getFileFileName() { return fileFileName; } public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; } }