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

  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>
原文地址:https://www.cnblogs.com/haoworld/p/struts2-wen-jian-shang-chuan-yu-xia-zai.html