Struts2文件上传下载
Struts2文件上传
Struts2提供 FileUpload拦截器,用于解析 multipart/form-data 编码格式请求,解析上传文件的内容,fileUpload拦截器 默认在defaultStack栈中, 默认会执行的
页面:<input type="file" name="upload" />
在Action需要对上传文件内容进行接收 :
private File upload; // <input type="file" name="upload" />这里变量名 和 页面表单元素 name 属性一致
private String uploadContentType;//格式 :上传表单项name属性 + ContentType 、 上传表单项name属性 + FileName
private String uploadFileName;
public void setUpload(File upload) {//为三个对象 提供 setter 方法
this.upload = upload;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
通过FileUtils 提供 copyFile 进行文件复制,将上传文件保存到服务器端
FileUtils.copyFile(upload, new File("d:/upload",uploadFileName));
关于struts2中文件上传细节:
1.关于控制文件上传大小
在default.properties文件中定义了文件上传大小:struts.multipart.maxSize=2097152 上传文件默认的总大小 2m
2.在struts2中默认使用的是commons-fileupload进行文件上传。
# struts.multipart.parser=cos
# struts.multipart.parser=pell
struts.multipart.parser=jakarta (如果使用pell,cos进行文件上传,必须导入其jar包)
3.如果出现问题,需要配置input视图,在页面上可以通过<s:actionerror>展示错误信息.在页面上展示的信息,全是英文,要想展示中文,国际化
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}
{0}:<input type=“file” name=“uploadImage”>中name属性的值
{1}:上传文件的真实名称
{2}:上传文件保存到临时目录的名称
{3}:上传文件的类型(对struts.messages.error.file.too.large是上传文件的大小)
4.关于多文件上传时的每个上传文件大小控制以及上传文件类型控制.
1.多文件上传
只需要将action属性声明成List集合或数组就可以。
private List<File> upload;
private List<String> uploadContentType;
private List<String> uploadFileName;
2.怎样控制每一个上传文件的大小以及上传文件的类型
在fileupload拦截器中,通过其属性进行控制.
maximumSize---每一个上传文件大小
allowedTypes--允许上传文件的mimeType类型.
allowedExtensions--允许上传文件的后缀名.
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedExtensions">txt,mp3,doc</param>
</interceptor-ref>
多文件上传案例:
import java.io.File;
import java.util.List;
import org.apache.commons.io.FileUtils;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
// 在action类中需要声明三个属性
private List<File> upload;
private List<String> uploadContentType;
private List<String> uploadFileName;
public List<File> getUpload() {
return upload;
}
public void setUpload(List<File> upload) {
this.upload = upload;
}
public List<String> getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(List<String> uploadContentType) {
this.uploadContentType = uploadContentType;
}
public List<String> getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(List<String> uploadFileName) {
this.uploadFileName = uploadFileName;
}
@Override
public String execute() throws Exception {
for (int i = 0; i < upload.size(); i++) {
System.out.println("上传文件的类型:" + uploadContentType.get(i));
System.out.println("上传文件的名称:" + uploadFileName.get(i));
// 完成文件上传.
FileUtils.copyFile(upload.get(i), new File("d:/upload", uploadFileName.get(i)));
}
return null;
}
}
UploadAction
<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>
upload.jsp
<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="cn.itcast.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>
struts.xml
struts2中文件下载
通过<result type="stream">完成
<result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
在StreamResult类中有三个属性:
protected String contentType = "text/plain"; //用于设置下载文件的mimeType类型
protected String contentDisposition = "inline";//用于设置进行下载操作以及下载文件的名称
protected InputStream inputStream; //用于读取要下载的文件。
要在action类中定义三个方法用于在XML文件中通过ognl获取值
// 设置下载文件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"); // 解决get请求中文名称乱码.
FileInputStream fis = new FileInputStream("d:/upload/" + filename);
return fis;
}
要在配置文件中配置
<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>
注:
1:在struts2中进行下载时,如果使用<result type="stream">它有缺陷,例如:下载点击后,取消下载,服务器端会产生异常。
在开发中的解决方案:可以下载一个struts2下载操作的插件,它解决了stream问题。
2:处理浏览器之间不同的编码的getDownloadFileName方法
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import sun.misc.BASE64Encoder; public class DownloadUtils { public static String getDownloadFileName(String agent, String filename) throws UnsupportedEncodingException {
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8"); } else if (agent.contains("Firefox")) {
// 火狐浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
filename = "=?utf-8?B?"
+ base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
} return filename;
}
}
DownloadUtils
下载案例:
<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>
download.jsp
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException; import org.apache.struts2.ServletActionContext; import cn.itcast.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;
} @Override
public String execute() throws Exception {
System.out.println("进行下载....");
return SUCCESS;
} }
DownloadAction
<action name="download" class="cn.itcast.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>
struts.xml
Struts2文件上传下载的更多相关文章
- JAVA Web 之 struts2文件上传下载演示(二)(转)
JAVA Web 之 struts2文件上传下载演示(二) 一.文件上传演示 详细查看本人的另一篇博客 http://titanseason.iteye.com/blog/1489397 二.文件下载 ...
- JAVA Web 之 struts2文件上传下载演示(一)(转)
JAVA Web 之 struts2文件上传下载演示(一) 一.文件上传演示 1.需要的jar包 大多数的jar包都是struts里面的,大家把jar包直接复制到WebContent/WEB-INF/ ...
- Struts2之文件上传下载
本篇文章主要介绍如何利用struts2进行文件的上传及下载,同时给出我在编写同时所遇到的一些问题的解决方案. 文件上传 前端页面 <!-- 引入struts标签 --> <%@tag ...
- Struts2文件上传和下载(原理)
转自:http://zhou568xiao.iteye.com/blog/220732 1. 文件上传的原理:表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:1) ...
- Struts2 文件上传,下载,删除
本文介绍了: 1.基于表单的文件上传 2.Struts 2 的文件下载 3.Struts2.文件上传 4.使用FileInputStream FileOutputStream文件流来上传 5.使用Fi ...
- 【SSH2(实用文章)】--Struts2文件上传和下载的例子
回想一下,再上一篇文章Struts2实现机制,该步骤做一步一步来解决,这种决心不仅要理清再次Struts2用法.映射机制及其在深入分析.最后一个例子来介绍Struts2一种用法,这里将做一个有关文件上 ...
- Struts2实现文件上传下载功能(批量上传)
今天来发布一个使用Struts2上传下载的项目, struts2为文件上传下载提供了好的实现机制, 首先,可以先看一下我的项目截图 关于需要使用的jar包,需要用到commons-fileupload ...
- 学习Struts--Chap07:Struts2文件上传和下载
1.struts2文件上传 1.1.struts2文件上传的基本概述 在开发web应用的时候,我们一般会为用户提供文件上传的功能,比如用户上传一张图像作为头像等.为了能上传文件,我们必须将表单的met ...
- struts2 文件上传和下载,以及部分源代码解析
struts2 文件上传 和部分源代码解析,以及一般上传原理 (1) 单文件上传 一.简单介绍 Struts2并未提供自己的请求解析器,也就是就Struts2不会自己去处理multipart/form ...
随机推荐
- iOS开发学习网站汇总
*本文转自CocoaChina 原文:11 Insanely Great iOS Developers Sites永不止步地向他人学习 我相信,要想从一个"还不错"的人变成一个卓越 ...
- (keymap设置及eclipse常用快捷键总结)
设置pycharm为Eclipse快捷键后使用总结: Ctrl + O 根据name模糊查找当前文件中类.方法 Alt + (向左箭头或者向右箭头) ,回退or前进到到之前查看或者编辑处 Alt + ...
- nyoj130 相同的雪花
相同的雪花 时间限制:1000 ms | 内存限制:65535 KB 难度:4 描述 You may have heard that no two snowflakes are alike. ...
- mysql时间字符串按年/月/天/时分组查询
SELECT DATE_FORMAT( deteline, "%Y-%m-%d %H" ) , COUNT( * ) FROM test GROUP BY DATE_FORMAT( ...
- 甲鱼od19篇随笔
在一个程序里会有多个对话框,这时要准确的判断要找的对话框就比较困难了所以这里就需要借助 1:Resource Hacker工具来准确的定位涉及到的对话框 2:在od中查找指令,然后在所有找到的指令上下 ...
- iOS-消息推送机制的实现
OS消息推送的工作机制可以简单的用下图来概括: Provider是指某个iPhone软件的Push服务器,APNS是Apple Push Notification Service的缩写,是苹果的服务器 ...
- 如何查看设备的 UDID
手机连接上电脑,打开 Xcode,确认手机已连上: command+shift+2,就可以查看到 UDID 了:
- iOS计算字符串的宽度高度
OC开发中会遇到根据字符串和字体大小来算计算出字符串所占的宽高->> 封装方法如下: #import <Foundation/Foundation.h> #import < ...
- js中我的注释规范
模块功能描述说明: /** * ------------------------------------------------------------------ * 模块描述说明 * ------ ...
- java Http原生 Get 和Post 支持代理认证
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import ...