struts2教程--实现文件上传下载
Struts2文件上傳下載
一、Struts2文件上傳
提供 FileUpload 攔截器,用于解析 multipart/form-data 編碼格式請求,解析上傳文件的內容
fileUpload攔截器 默認在 defaultStack棧中, 默認會執行的
在Action需要對上傳文件內容進行接收
頁面:
<input type="file" name="upload" />Action:
public class UploadAction extends ActionSupport {// 接收上傳內容// <input type="file" name="upload" />private File upload; // 這里變量名 和 頁面表單元素 name 屬性一致private String uploadContentType;private String uploadFileName;}
注意:
格式 : 上傳表單項name屬性+ ContentType、 上傳表單項name屬性+ FileName
為三個對象 提供 setter方法
通過FileUtils 提供copyFile進行文件復制,將上傳文件 保存到服務器端
二、Struts2文件上傳問題解決
1、配置 input 視圖 ,作為上傳出錯后 跳轉頁面
在文件上傳時,如果發生錯誤 ,fileUpload攔截器 會設置錯誤信息,workflow攔截器 跳轉到input視圖
2、struts.multipart.parser=jakarta 定義文件上傳,采用 commons-fileupload 技術
?同時支持 cos、pell上傳技術 (如果使用其它上傳技術,單獨下載jar包 )
3、通過 struts.multipart.maxSize 常量設置文件上傳總大小限制
??? struts.multipart.maxSize=2097152 默認上傳文件總大小 2MB
?超過文件總大小,跳轉input視圖, 通過<s:actionError />回顯錯誤信息
4、在struts.xml 設置上傳總大小
<constant name="struts.multipart.maxSize" value="20000000"></constant>
?
5、設置上傳文件總大小,對所有上傳form有效,只想對當前form進行設置,可以設置fileUpload攔截器屬性
FileUpload 攔截器有 3個屬性可以設置.
* maximumSize: 上傳文件的最大長度(以字節為單位),默認值為2 MB
* allowedTypes: 允許上傳文件的類型,各類型之間以逗號分隔
* allowedExtensions: 允許上傳文件擴展名,各擴展名之間以逗號分隔
如果針對fileUpload 進行參數設置,當出錯時,在頁面通過 <s:fieldError />回顯錯誤信息
struts-messages.properties 文件里預定義 上傳錯誤信息,通過覆蓋對應key顯示中文信息
struts.messages.error.uploading=Error uploading: {0}
struts.messages.error.file.too.large=The file is to large to be uploaded: {0} "{1}" "{2}" {3}
struts.messages.error.content.type.not.allowed=Content-Type not allowed: {0} "{1}" "{2}" {3}
struts.messages.error.file.extension.not.allowed=File extension not allowed: {0} "{1}" "{2}" {3}
修改為
struts.messages.error.uploading=上傳錯誤: {0}
struts.messages.error.file.too.large=上傳文件太大: {0} "{1}" "{2}" {3}
struts.messages.error.content.type.not.allowed=上傳文件的類型不允許: {0} "{1}" "{2}" {3}
struts.messages.error.file.extension.not.allowed=上傳文件的后綴名不允許: {0} "{1}" "{2}" {3}
上傳案例:
jsp頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>My JSP 'index.jsp' starting page</title></head><body><s:fielderror/><s:actionerror/><form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data"><input type="file" name="upload"><br><input type="file" name="upload"><br><input type="file" name="upload"><br><input type="submit" value="上傳"></form></body> </html>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><constant name="struts.custom.i18n.resources" value="message"></constant><constant name="struts.multipart.maxSize" value="20971520"></constant><package name="default" namespace="/" extends="struts-default"><action name="upload" class="com.sihai.action.UploadAction"><result name="input">/upload.jsp</result><interceptor-ref name="defaultStack"><param name="maximumSize">2097152</param><param name="fileUpload.allowedExtensions">txt,mp3,doc</param></interceptor-ref></action></package> </struts> com.sihai.action.UploadAction"><result name="input">/upload.jsp</result><interceptor-ref name="defaultStack"><param name="maximumSize">2097152</param><param name="fileUpload.allowedExtensions">txt,mp3,doc</param></interceptor-ref></action></package> </struts>
action:
三、多文件上傳
第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。這兩個文件可以從http://commons.apache.org/下載。
第二步:把form表的enctype設置為:“multipart/form-data“,如下:
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post"><input type="file" name="uploadImages"><input type="file" name="uploadImages"></form>第三步:在Action類中添加以下屬性,屬性紅色部分對應于表單中文件字段的名稱:
public class uploadAction{private File[] uploadImages;//得到上傳的文件private String[] uploadImagesContentType;//得到文件的類型private String[] uploadImagesFileName;//得到文件的名稱//這里略省了屬性的getter/setter方法public String saveFiles() throws Exception{ServletContext sc = ServletActionContext.getServletContext();String realpath = sc.getRealPath("/uploadfile");try {if(uploadImages!=null&&uploadImages.length>0){for(int i=0;i<uploadImages.length;i++){File destFile = new File(realpath,uploadImageFileNames[i]);FileUtils.copyFile(uploadImages[i], destFile);}}} catch (IOException e) {e.printStackTrace();}return "success";}}四、Struts2文件下載
1) struts2完成文件下載,通過 結果集類型 (Result Type)stream來完成的
?struts-default.xml 定義 <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
2) 使用Stream結果集 完成文件下載
文件下載原理: 服務器讀取下載文件內容,通過Response響應流寫回, 設置ContentType、ContentDisposition頭信息
public class StreamResult extends StrutsResultSupport {protected String contentType = "text/plain"; // contentType頭信息 (下載文件對應 MIME協議規定類型 )protected String contentDisposition = "inline"; // ContentDisposition頭信息 (下載文件打開方式 inline瀏覽器內部打開, attachment 以附件形式打開)protected String inputName = "inputStream"; // 需要Action中 提供 getInputStream 方法 返回 InputStream 提供下載文件 內容}3)Action 提供 InputStream ?返回值getInputStream方法-------指定下載文件流
配置 stream 結果集 參數<param name="contentType">${contentType}</param> ----在Action中提供getContentType
ServletActionContext.getServletContext().getMimeType(filename);
配置 stream 結果集 參數<param name="contentDisposition">attachment;filename=${filename}</param> ----在Action提供getFilename
下載附件名亂碼問題
public String encodeDownloadFilename(String filename, String agent)throws IOException {if (agent.contains("Firefox")) { // 火狐瀏覽器filename = "=?UTF-8?B?"+ new BASE64Encoder().encode(filename.getBytes("utf-8"))+ "?=";} else { // IE及其他瀏覽器filename = URLEncoder.encode(filename, "utf-8");}return filename;}文件下載案例
jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head><title>My JSP 'index.jsp' starting page</title></head><body><a href="${pageContext.request.contextPath}/download?filename=a.txt">a.txt</a><br><a href="${pageContext.request.contextPath}/download?filename=捕獲.png">捕獲.png</a><br> </body> </html>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><constant name="struts.custom.i18n.resources" value="message"></constant><constant name="struts.multipart.maxSize" value="20971520"></constant><package name="default" namespace="/" extends="struts-default"><action name="download" class="com.sihai.action.DownloadAction"><result type="stream"><param name="contentType">${contentType}</param> <!-- 調用當前action中的getContentType()方法 --><param name="contentDisposition">attachment;filename=${downloadFileName}</param><param name="inputStream">${inputStream}</param><!-- 調用當前action中的getInputStream()方法 --></result></action></package> </struts> package com.sihai.action;import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.UnsupportedEncodingException;import org.apache.struts2.ServletActionContext;import com.sihai.utils.DownloadUtils;import com.opensymphony.xwork2.ActionSupport;public class DownloadAction extends ActionSupport {private String filename; // 要下載文件的名稱public String getFilename() {return filename;}public void setFilename(String filename) {this.filename = filename;}// 設置下載文件mimeType類型public String getContentType() {String mimeType = ServletActionContext.getServletContext().getMimeType(filename);return mimeType;}// 獲取下載文件名稱public String getDownloadFileName() throws UnsupportedEncodingException {return DownloadUtils.getDownloadFileName(ServletActionContext.getRequest().getHeader("user-agent"), filename);}public InputStream getInputStream() throws FileNotFoundException,UnsupportedEncodingException {filename = new String(filename.getBytes("iso8859-1"), "utf-8"); // 解決中文名稱亂碼.FileInputStream fis = new FileInputStream("d:/upload/" + filename);return fis;}@Overridepublic String execute() throws Exception {System.out.println("進行下載....");return SUCCESS;}}總結
以上是生活随笔為你收集整理的struts2教程--实现文件上传下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: struts2教程(8)--文件上传下载
- 下一篇: struts2教程(9)--OGNL表达