【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,只有设置为这种情况下,浏览器才会把用户选择文件的二进制数据发送给服务器. 上传 ...
随机推荐
- 图解 HTTP 笔记(三)—— HTTP 报文内的 HTTP 信息
本章主要讲解请求和响应是如何运作的 一.HTTP 报文 用于 HTTP 协议交互的信息被称为 HTTP 报文,客户端的 HTTP 报文叫做请求报文,服务器端的叫做响应报文. HTTP 报文大致可分为报 ...
- CockroachDB学习笔记——[译]在CockroachDB中如何让在线模式更改成为可能
原文链接:https://www.cockroachlabs.com/blog/how-online-schema-changes-are-possible-in-cockroachdb/ 原作者: ...
- react中 如何异步展示后台接口的提示消息
调用接口后,后台会返回这样的一段信息提示:{"errCode":400002,"errMsg":"字段校验异常","data&qu ...
- C#操作Memcached帮助类
在VS中安装Memcached,直接在NuGet下搜索Memcached,选择第一个进行安装: 服务端资源下载地址:https://pan.baidu.com/s/1gf3tupl 接下来开始写程序, ...
- 最新 新华网java校招面经 (含整理过的面试题大全)
从6月到10月,经过4个月努力和坚持,自己有幸拿到了网易雷火.京东.去哪儿.新华网等10家互联网公司的校招Offer,因为某些自身原因最终选择了新华网.6.7月主要是做系统复习.项目复盘.LeetCo ...
- Mysql 索引失效场景
例如:一张USER表 有字段属性 name,age 其中name为索引 下面列举几个索引失效的情况 1. select * from USER where name=‘xzz’ or age= ...
- poj1269 (叉积求直线的交点)
题目链接:https://vjudge.net/problem/POJ-1269 题意:给出4个顶点,表示两条直线,求这两条直线的相交情况,重合输出LINE,平行输出NONE,相交于一点输出该点的距离 ...
- EXCEL 查找某个字符在字符串中最后一次出现的位置
在EXCEL文档里想从很长的文件路径中取得文件名,[数据]→[分列]是个不错的选择,但用函数会显得更高大上一些. 首先,需要获取最后一个"\"所在的位置. 方法1: FIND(&q ...
- 【AtCoder】AGC010
AGC010 A - Addition 如果所有数加起来是偶数那么一定可以,否则不行 #include <bits/stdc++.h> #define fi first #define s ...
- Hello TypeScript
⒈TypeScript简介 1.JavaScript的超集 2.支持ECMAScript6标准,并支持输出ECMAScript3/5/6标准的纯JavaScript代码 3.支持ECMAScript未 ...