【Struts2】文件上传与下载
一、上传
1.1 Struts2实现步骤
浏览器端
- 上传文件的标签要满足下面三个条件:
method=post
<input type="file" name="xx">
encType="multipart/form-data";
服务器端
依赖于 commons-fileupload组件
- 1.DiskFileItemFactory
- 2.ServletFileUpload
- 3.FileItem
struts2中文件上传:
- 默认情况下struts2框架使用的就是commons-fileupload组件.
- struts2它使用了一个interceptor帮助我们完成文件上传操作。
<interceptor name="fileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"/>
页面上组件:
在action中要有三个属性:
private File upload;
private String uploadContentType;
private String uploadFileName;
- 在execute方法中使用commons-io包下的FileUtils完成文件复制.
java
FileUtils.copyFile(upload, new File("d:/upload",uploadFileName));
1.2 关于Struts2中文件上传细节:
- 关于控制文件上传大小
- 在default.properties文件中定义了文件上传大小
- struts.multipart.maxSize=2097152 上传文件默认的总大小 2m
在struts2中默认使用的是commons-fileupload进行文件上传。在struts2的常量文件中有如下声明,如果使用pell,cos进行文件上传,必须导入其jar包.
# struts.multipart.parser=cos
# struts.multipart.parser=pell
struts.multipart.parser=jakarta
如果出现问题,需要配置input视图,在页面上可以通过展示错误信息. 问题:在页面上展示的信息,全是英文,要想展示中文,国际化
#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是上传文件的大小)
关于多文件上传时的每个上传文件大小控制以及上传文件类型控制.
- 服务器端:只需要将action属性声明成List集合或数组就可以。
private List<File> upload;
private List<String> uploadContentType;
private List<String> uploadFileName;
- 浏览器端:
<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>
怎样控制每一个上传文件的大小以及上传文件的类型?
- 在fileupload拦截器中,通过其属性进行控制.
- maximumSize---每一个上传文件大小
- allowedTypes--允许上传文件的mimeType类型.
- allowedExtensions--允许上传文件的后缀名.
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedExtensions">txt,mp3,doc</param>
</interceptor-ref>
1.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>
Action类
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;
}
}
struts.xml文件配置
<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.hao.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>
二、下载
2.1 文件下载方式
- 超连接
- 服务器编码,通过流向客户端写回。
- 通过response设置
response.setContentType(String mimetype);
- 通过response设置
response.setHeader("Content-disposition;filename=xxx");
- 通过response获取流,将要下载的信息写出。
- 通过response设置
2.2 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类中定义一个方法
public InputStream getInputStream() throws FileNotFoundException {
FileInputStream fis = new FileInputStream("d:/upload/" + filename);
return fis;
}
struts.xml 中配置
<result type="stream">
<param name="contentType">text/plain</param>
<param name="contentDisposition">attachment;filename=a.txt</param>
<param name="inputStream">${inputStream}</param> 会调用当前action中的getInputStream方法。
</result>
问题1:
<a href="${pageContext.request.contextPath}/download?filename=捕获.png">捕获.png</a>
下载报错原因:超连接是get请求,并且下载的文件是中文名称,乱码。
问题2:下载捕获文件时,文件名称就是a.txt,下载文件后缀名是png,而我们在配置文件中规定就是txt?
<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>
在struts2中进行下载时,如果使用它有缺陷,例如:下载点击后,取消下载,服务器端会产生异常。
在开发中,解决方案:可以下载一个struts2下载操作的插件,它解决了stream问题。
示例代码
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>
Action类
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;
}
}
struts.xml 文件配置
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="download" class="com.hao.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>
【Struts2】文件上传与下载的更多相关文章
- Struts2文件上传和下载(原理)
转自:http://zhou568xiao.iteye.com/blog/220732 1. 文件上传的原理:表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:1) ...
- 十六、Struts2文件上传与下载
文件上传与下载 1.文件上传前提:<form action="${pageContext.request.contextPath}/*" method="post& ...
- 【SSH2(实用文章)】--Struts2文件上传和下载的例子
回想一下,再上一篇文章Struts2实现机制,该步骤做一步一步来解决,这种决心不仅要理清再次Struts2用法.映射机制及其在深入分析.最后一个例子来介绍Struts2一种用法,这里将做一个有关文件上 ...
- 学习Struts--Chap07:Struts2文件上传和下载
1.struts2文件上传 1.1.struts2文件上传的基本概述 在开发web应用的时候,我们一般会为用户提供文件上传的功能,比如用户上传一张图像作为头像等.为了能上传文件,我们必须将表单的met ...
- struts2 文件上传和下载,以及部分源代码解析
struts2 文件上传 和部分源代码解析,以及一般上传原理 (1) 单文件上传 一.简单介绍 Struts2并未提供自己的请求解析器,也就是就Struts2不会自己去处理multipart/form ...
- (八)Struts2 文件上传和下载
所有的学习我们必须先搭建好Struts2的环境(1.导入对应的jar包,2.web.xml,3.struts.xml) 第一节:Struts2 文件上传 Struts2 文件上传基于Struts2 拦 ...
- struts2学习(13)struts2文件上传和下载(1)
一.Struts2文件上传: 二.配置文件的大小以及允许上传的文件类型: 三.大文件上传: 如果不配置上传文件的大小,struts2默认允许上传文件最大为2M: 2097152Byte: 例子实现 ...
- Struts2文件上传与下载
一,页面 index.html 在页面中最重要的就是这个文件上传用的 form 表单,注意这里一定要把 form 的encyType属性明确标定为“multipart/form-data”,只有这样. ...
- struts2文件上传和下载
1. struts系统中的拦截器介绍 过滤器:javaweb中的服务器组件,主要针对的请求和响应进行拦截. 拦截器:主要针对方法的调用,进行拦截器,当使用代理对象调用某个方法时候 对方法的调用进行拦截 ...
- 笔记:Struts2 文件上传和下载
为了上传文件必须将表单的method设置为POST,将 enctype 设置为 muiltipart/form-data,只有设置为这种情况下,浏览器才会把用户选择文件的二进制数据发送给服务器. 上传 ...
随机推荐
- Python基础-day04
函数基础 目标 函数的快速体验 函数的基本使用 函数的参数 函数的返回值 函数的嵌套调用 在模块中定义函数 01. 函数的快速体验 1.1 快速体验 所谓函数,就是把 具有独立功能的代码块 组织为一个 ...
- LeetCode_13. Roman to Integer
13. Roman to Integer Easy Roman numerals are represented by seven different symbols: I, V, X, L, C, ...
- linux查看文件具体时间和大小
查看具体时间 ll --full-time 查看文件大小: ll -ht 或者du -sh *
- Spark + sbt + IDEA + HelloWorld + MacOS
构建项目步骤 首先要安装好scala.sbt.spark,并且要知道对应的版本 sbt版本可以在sbt命令行中使用sbtVersion查看 spark-shell可以知晓机器上spark以及对应的sc ...
- 深入浅出的分析 Set集合
01. 摘要 Set集合的特点主要有:元素不重复.存储无序的特点. 打开 Set 集合,主要实现类有 HashSet.LinkedHashSet .TreeSet .EnumSet( RegularE ...
- Windows下的3389端口渗透
1.Win7.Win2003.XP系统 在CMD命令行开启3389端口:REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Terminal" &qu ...
- linux中alarm函数和pause函数详解实例
alarm(time);执行之后告诉内核,让内核在time秒时间之后向该进程发送一个定时信号,然后该进程捕获该信号并处理:pause()函数使该进程暂停让出CPU,但是该函数的暂停和前面的那个slee ...
- noi openjudge7627:鸡蛋的硬度
http://noi.openjudge.cn/ch0206/7627/ 描述 最近XX公司举办了一个奇怪的比赛:鸡蛋硬度之王争霸赛.参赛者是来自世界各地的母鸡,比赛的内容是看谁下的蛋最硬,更奇怪的是 ...
- Spring mybatis源码篇章-Mybatis主文件加载
通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-SqlSessionFactory 前话 本文承接前文的内容继续往下扩展,通过Spring与Mybatis的 ...
- js 中json遍历 添加 修改 类型转换
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...