一、上传

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中文件上传细节:

  1. 关于控制文件上传大小

    • 在default.properties文件中定义了文件上传大小
    • struts.multipart.maxSize=2097152 上传文件默认的总大小 2m
  2. 在struts2中默认使用的是commons-fileupload进行文件上传。在struts2的常量文件中有如下声明,如果使用pell,cos进行文件上传,必须导入其jar包.

    # struts.multipart.parser=cos
    # struts.multipart.parser=pell
    struts.multipart.parser=jakarta
  3. 如果出现问题,需要配置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是上传文件的大小)
  4. 关于多文件上传时的每个上传文件大小控制以及上传文件类型控制.

    • 服务器端:只需要将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>
  5. 怎样控制每一个上传文件的大小以及上传文件的类型?

    • 在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 文件下载方式

  1. 超连接
  2. 服务器编码,通过流向客户端写回。
    • 通过response设置 response.setContentType(String mimetype);
    • 通过response设置 response.setHeader("Content-disposition;filename=xxx");
    • 通过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】文件上传与下载的更多相关文章

  1. Struts2文件上传和下载(原理)

    转自:http://zhou568xiao.iteye.com/blog/220732 1.    文件上传的原理:表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:1)     ...

  2. 十六、Struts2文件上传与下载

    文件上传与下载 1.文件上传前提:<form action="${pageContext.request.contextPath}/*" method="post& ...

  3. 【SSH2(实用文章)】--Struts2文件上传和下载的例子

    回想一下,再上一篇文章Struts2实现机制,该步骤做一步一步来解决,这种决心不仅要理清再次Struts2用法.映射机制及其在深入分析.最后一个例子来介绍Struts2一种用法,这里将做一个有关文件上 ...

  4. 学习Struts--Chap07:Struts2文件上传和下载

    1.struts2文件上传 1.1.struts2文件上传的基本概述 在开发web应用的时候,我们一般会为用户提供文件上传的功能,比如用户上传一张图像作为头像等.为了能上传文件,我们必须将表单的met ...

  5. struts2 文件上传和下载,以及部分源代码解析

    struts2 文件上传 和部分源代码解析,以及一般上传原理 (1) 单文件上传 一.简单介绍 Struts2并未提供自己的请求解析器,也就是就Struts2不会自己去处理multipart/form ...

  6. (八)Struts2 文件上传和下载

    所有的学习我们必须先搭建好Struts2的环境(1.导入对应的jar包,2.web.xml,3.struts.xml) 第一节:Struts2 文件上传 Struts2 文件上传基于Struts2 拦 ...

  7. struts2学习(13)struts2文件上传和下载(1)

    一.Struts2文件上传: 二.配置文件的大小以及允许上传的文件类型: 三.大文件上传: 如果不配置上传文件的大小,struts2默认允许上传文件最大为2M: 2097152Byte:   例子实现 ...

  8. Struts2文件上传与下载

    一,页面 index.html 在页面中最重要的就是这个文件上传用的 form 表单,注意这里一定要把 form 的encyType属性明确标定为“multipart/form-data”,只有这样. ...

  9. struts2文件上传和下载

    1. struts系统中的拦截器介绍 过滤器:javaweb中的服务器组件,主要针对的请求和响应进行拦截. 拦截器:主要针对方法的调用,进行拦截器,当使用代理对象调用某个方法时候 对方法的调用进行拦截 ...

  10. 笔记:Struts2 文件上传和下载

    为了上传文件必须将表单的method设置为POST,将 enctype 设置为 muiltipart/form-data,只有设置为这种情况下,浏览器才会把用户选择文件的二进制数据发送给服务器. 上传 ...

随机推荐

  1. 阶段5 3.微服务项目【学成在线】_day04 页面静态化_02-freemarker介绍

  2. 阶段5 3.微服务项目【学成在线】_day02 CMS前端开发_10-webpack研究-安装nodejs

    1.3.2.1 安装Node.js webpack基于node.js运行,首先需要安装node.js. node -v:验证是否安装成功了.

  3. 在谷歌中缓存下载视频离线观看,js代码

    var download=function(urlInfo) { when(createFile(localFileName)) .then(function (fileInfo) { var dow ...

  4. Cannon 60D 电池卡在电池槽了,拔不出来怎么办?

    事情是这样的,本来好好的电池在电池槽里的,后来拿去充电了,充满后就准备装回去,然后一个不小心,电池掉地上了,就看了一下没摔爆,所以也没特别留意有没有什么地方摔坏摔瘸角,然后就往相机里塞,突然就发现塞不 ...

  5. Volatility取证使用笔记

    最近简单的了解了一下Volatility这个开源的取证框架,这个框架能够对导出的内存镜像镜像分析,能过通过获取内核的数据结构,使用插件获取内存的详细情况和运行状态,同时可以直接dump系统文件,屏幕截 ...

  6. Insomni’hack CTF-l33t-hoster复现分析

    题目地址: https://github.com/eboda/insomnihack/tree/master/l33t_hoster 源码如下: <?php if (isset($_GET[&q ...

  7. ZoomEye

    * https://www.zoomeye.org/ *类似工具 IVRE 1. 摄像头漏洞 (1)http://www.2cto.com/Article/201401/269458.html (2) ...

  8. [转帖]phoronix-test-suite测试云服务器

    phoronix-test-suite测试云服务器 https://www.cnblogs.com/tanyongli/p/7767804.html centos系统 phoronix-test-su ...

  9. IDEA插件之JavaDoc

      作用:用于在Java类元素(例如字段,方法等)上生成Java文档的插件.   1.安装JavaDoc插件 File -> Settings -> Plugins -> Marke ...

  10. Kubernetes---Pod笔记

    ⒈pod的理解     将多个容器镜像融合在一起,共享网络命名空间及容器卷 ⒉pod的分类 自助式podv          不是被控制器管理的pod,它一旦死亡不会被人给拉起来. 控制器管理的pod ...