一、上传

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. uni-app 使用Vuex+ (强制)登录

    一.在项目的根目录下新建一个store文件夹,然后在文件夹下新建一个index.js文件 二.在新建的index.js下引入vue和vuex,具体如下: //引入vue和vuex import Vue ...

  2. 移动端BI的设计

    在移动化.大数据浪潮的今天,基于数据做决策应该是每一家公司的标配:每家公司都有专门负责数据的人,也都应该有一个BI部门.而移动BI,基于手机端随时随地进行数据查询和分析——更是BI中不可或缺的一部分. ...

  3. ubuntu下virtualbox的安装、卸载

    一.添加VirtualBox的源并安装5.1版本 virtualbox官网:https://www.virtualbox.org/wiki/Download_Old_Builds 虽然也可以直接安装d ...

  4. Spring Boot连接MySQL长时间不连接后报错`com.mysql.cj.core.exceptions.ConnectionIsClosedException: No operations allowed after connection closed.`的解决办法

    报错:com.mysql.cj.core.exceptions.ConnectionIsClosedException: No operations allowed after connection ...

  5. Android之view的工作原理2

    学习内容 View的底层工作原理,比如View的测量流程.布局流程以及绘制流程:以及常见的View回调方法:熟悉掌握前面的知识后,自定义View的时候也会更加的得心应手. 4.1 初识ViewRoot ...

  6. vue-cli3项目运行时一直发http://localhost:8080/sockjs-node/info?t=1462183700002请求

    报错如下图: 解决方式: 一.如果是在开发环境,应该是开发的时候网络环境变更导致,比如你切换无线网络,导致开发服务器的IP地址换了,这样开发服务器会不知道如何确定访问源.开发环境中关闭npm dev ...

  7. Matlab求微分方程的符号解1

    一.常微分方程的求解 例1. 例2. 例3. 通常我们使用syms 和dsolve来求解: first: second:表示 third:如果有必要 功能函数diff可以完成一元或多元函数任意阶数的微 ...

  8. BIO和NIO实现文件复制

    普通文件复制 public void copyFile() throws Exception{ FileInputStream fis=new FileInputStream("C:\\Us ...

  9. Spark Scala当中reduce的用法和例子

    [学习笔记] reduce将RDD中元素前两个传给输入函数,产生一个新的return值,将新产生的return值与RDD中下一个元素(即第三个元素)组成两个元素,再被传给输入函数,这样递归运作,直到最 ...

  10. day04_XPATH提取数据

    1.XML简介 1.1.定义 ​ 可扩展标记语言(EXtensible Markup Language) 1.2.特点 一种标记语言,很类似 HTML XML 的标签需要我们自行定义 被设计为具有自我 ...