1. 程式人生 > >Struts2之檔案上傳與下載

Struts2之檔案上傳與下載

1、檔案上傳三種方式:

  • 將檔案以二進位制的形式儲存到資料庫中 activiti工作流框架 
  • 將檔案儲存到專門檔案伺服器(存放檔案用的Linux系統)中
  •  直接將檔案儲存到伺服器(tomcat所在伺服器)中

2、檔案上傳的一個例項:

action裡的程式碼如下: 

        private File file;//虛擬路徑
	private String fileContentType;//檔案型別
	private String fileFileName;//檔名
	
	private String serverDir="/upload";//伺服器中檔案儲存的資料夾(不用自己新建)
	
	/**
	 * 上傳
	 * @author LJ
	 * @Date 2018年10月15日
	 * @Time 上午11:53:40
	 * @return
	 */
	public String upload() {
		String realPath=getRealPath(serverDir+"/"+fileFileName);
		try {
            //檔案上傳的關鍵方法
			FileUtils.copyFile(file, new File(realPath));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 獲取Linux目錄的真實路徑
	 * @author LJ
	 * @Date 2018年10月15日
	 * @Time 上午11:26:53
	 * @param path:指的是本地路徑(相對於工程WebContent所在的路徑)
	 * @return
	 */
	private String getRealPath(String path) {
		return application.getRealPath(path);
	}

注:前三個變數的變數名是Struts2裡固定的,不能更改,此外,還需要給它們提供set/get方法

jsp頁面的程式碼如下:

        <form action="${pageContext.request.contextPath }/sy/uploadAction_upload.action" enctype="multipart/form-data" method="post">
		<input type="file" name="file" >
		<input type="submit" value="上傳" >
	</form>

注:enctype="multipart/form-data" method="post"也是固定的,宣告表單是特殊的提交方式

3、檔案下載的一個例項:

action裡的程式碼如下:

/**
	 * 下載圖片
	 * @author LJ
	 * @Date 2018年10月15日
	 * @Time 下午2:33:36
	 * @return
	 */
	public String saveAs() {
		String type="image/jpeg";//要下載檔案的型別
		String name="5.jpg";//要下載檔案的檔名
		response.setContentType(type);
		response.setHeader("Content-Disposition","attachment;filename=" + name);//設定響應頭
		File servletFile=new File(getRealPath(serverDir + "/" + name));//在伺服器中找到該檔案
		try {
			//用Struts自己的方法下載
//			FileUtils.copyFile(servletFile, response.getOutputStream());
			//用快取流下載
			BufferedInputStream bit=new BufferedInputStream(new FileInputStream(servletFile));
			BufferedOutputStream bos=new BufferedOutputStream(response.getOutputStream());
			copyByBuffered(bit, bos);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 用快取流下載(提高效能)
	 * @author LJ
	 * @Date 2018年10月15日
	 * @Time 下午10:33:28
	 * @param in
	 * @param out
	 * @throws IOException
	 */
	private void copyByBuffered(BufferedInputStream in, BufferedOutputStream out) throws IOException {
		byte[] bt=new byte[1024];
		int len=0;
		while((len=in.read(bt))!=-1) {
			out.write(bt, 0, len);
		}
		in.close();
		out.close();
	}

jsp頁面的程式碼如下:

        <s:url action="uploadAction_saveAs" namespace="/sy" var="saveUrl"></s:url>
	<s:a href="%{#saveUrl}">儲存</s:a>

4、展示上傳的檔案:

action裡的程式碼如下:

        /**
	 * 開啟圖片
	 * @author LJ
	 * @Date 2018年10月15日
	 * @Time 下午12:00:03
	 * @return
	 */
	public String openAs() {
		String type="image/jpeg";//要開啟檔案的型別
		String name="5.jpg";//要開啟檔案的檔名
		response.setContentType(type);//內容型別
		response.setHeader("Content-Disposition","filename=" + name);//設定響應頭
		/*
		 * 從伺服器拿圖片到本地
		 * 源:伺服器
		 * 目的:jsp輸出圖片
		 */
		File servletFile=new File(getRealPath(serverDir + "/" + name));
		try {
			FileUtils.copyFile(servletFile, response.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

注: 檔案下載與展示的設定響應頭的第二個引數只差一個attachment

jsp頁面的程式碼如下:

        <s:url action="uploadAction_openAs" namespace="/sy" var="openUrl"></s:url>
	<img alt="img" src='<s:property value="#openUrl" />'>

附:

處理檔名的中文亂碼:
String fileName = d.getFileName();
 fileName = new String(fileName.getBytes("utf-8"), "iso8859-1");

struts2檔案上傳大小設定:
<!-- 指定允許上傳的檔案最大位元組數。預設值是2097152(2M) 10M=10*1024*1024 -->
<constant name="struts.multipart.maxSize" value="10485760"/>

struts2檔案上傳型別設定(通過配置攔截器):
根據struts2自帶的fileupload攔截器中提供的allowedTypes來進行限制
<interceptor-ref name="fileUpload">
     <param name="allowedTypes">image/png,image/gif,image/jpeg</param>
</interceptor-ref>