Struts2檔案上傳與檔案下載
阿新 • • 發佈:2021-01-05
Struts2預設攔截器棧中包含一個檔案上傳攔截器,其底層實現依賴apache的commons.fileUpload,網頁表單則可通過Struts2的檔案上傳攔截器直接上傳檔案。
攔截器將客戶端上傳的檔案自動存放至系統臨時目錄,Struts2的Action需要做的就是將臨時目錄中的檔案通過IO流轉存至指定目錄。
注意:
① 檔案上傳時需要注意struts2-core-2.3.37.jar\org.apache.struts2\default.properties中的檔案上傳大小限制
② JSP頁面檔案上傳表單form需加上enctype=“multipart/form-data”
檔案上傳Action:
package action; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; public class UploadAction { private File[] images; // 此處命名必須以File型別檔案屬性名稱 + FileName結尾,否則無法識別 private String[] imagesFileName; // 此處省略欄位的Getters和Setters public String execute() { // 考慮images[]未建立的情況,預防未選擇任何檔案而直接提交時觸發的空指標異常 if (null != images) { for (int i = 0; i < images.length; i++) { try { // 實際Web專案無權操作客戶機的檔案路徑,僅專案路徑可供使用 String path = ServletActionContext.getServletContext().getRealPath("/images"); File destFile = new File(path, imagesFileName[i]); FileUtils.copyFile(images[i], destFile); } catch (IOException e) { e.printStackTrace(); } } return "success"; } return "message"; } }
服務端向客戶端傳送瀏覽器支援的檔案型別(如txt、jpg等)時會直接在瀏覽器中顯示,反之若服務端要求使用者以附件的形式儲存檔案則另稱為檔案下載。向瀏覽器提供檔案下載功能需要設定HTTP響應頭的Content-Disposition=attachment。
Action類中需要提供檔案輸入流(用於指定伺服器向客戶端提供下載的檔案資源)和檔名(使用者下載的資原始檔名稱)兩個屬性,struts.xml配置檔案中對應Action的result標籤的type宜設定為stream。
檔案下載Action:
package action; import java.io.InputStream; import java.io.UnsupportedEncodingException; import org.apache.struts2.ServletActionContext; public class DownloadAction { private InputStream is; // 此處的檔名稱無需仿照檔案上傳時的xxxFileName,命名規範即可 private String fileName; // 此處省略欄位的Getters和Setters public String execute() throws UnsupportedEncodingException { fileName = "16.jpeg"; // 將專案pojoImgs下的16.jpeg作為資源下載目標 is = ServletActionContext.getServletContext().getResourceAsStream("/pojoImgs/" + fileName); // 手動指定資源下載時的檔名稱,實際宜從DB中載入 fileName = "下載測試.jpeg"; // 解決中文資源名稱亂碼問題:先以utf-8拆解,再以ISO-8859-1組裝 byte[] bytes = fileName.getBytes("utf-8"); fileName = new String(bytes, "ISO-8859-1"); return "success"; } }
struts.xml(重要)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 手動指定default.properties中總上傳檔案大小的限制 -->
<constant name="struts.multipart.maxSize" value="20971520"/>
<package name="strutsFiles" namespace="/upAndDownload" extends="struts-default">
<action name="uploadAction" class="action.UploadAction">
<result name="success">/welcome.jsp</result>
<result name="message">/message.jsp</result>
<!-- 指定上傳檔案的副檔名 -->
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedExtensions">bmp,gif,jpg,jpeg,png,webp</param>
</interceptor-ref>
</action>
<action name="downloadAction" class="action.DownloadAction">
<result type="stream">
<!-- 指定檔案資源以存於Action中的fileName屬性值命名 -->
<param name="contentDisposition">attachment;filename=${fileName}</param>
<!-- param標籤的name屬性值預設為inputName -->
<!-- 當且僅當檔案下載Action中的InputStream名為inputStream時此句可省略 -->
<param name="inputName">is</param> <!-- is為檔案下載Action中的InputStream名稱 -->
</result>
</action>
</package>
</struts>
WebRoot目錄結構:
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<!-- form的enctype="multipart/form-data"屬性值是表單檔案上傳的必填選項 -->
<form action="upAndDownload/uploadAction" method="post" enctype="multipart/form-data">
請選擇圖片:<br /><br />
<input type="file" name="images" /><br /><br />
<input type="file" name="images" /><br /><br />
<input type="file" name="images" /><br /><br />
<input type="submit" value="上傳" />
</form><br /><br />
<a href="upAndDownload/downloadAction">下載一張圖片...</a>
</body>
</html>
message.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Message</title>
</head>
<body>
<h3 align="center">檔案上傳失敗!</h3>
</body>
</html>
welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<h3 align="center">檔案上傳成功!</h3>
</body>
</html>