Struts2] [file upload and download

First, upload

1.1 Struts2 implementation steps

Browser

  • Label upload files to meet the following three conditions:
    • method=post
    • <input type="file" name="xx">
    • encType="multipart/form-data";

Service-Terminal

  • Component depends on the commons-fileupload

    • 1.DiskFileItemFactory
    • 2.ServletFileUpload
    • 3.FileItem
  • struts2 file upload:

    • The default is commons-fileupload struts2 frame assembly used in the case.
    • It uses an interceptor struts2 help us complete the file upload operation.
    <interceptor name="fileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"/>
    
  • Components on the page:

  • In the action should have three properties:

private File upload;
private String uploadContentType;
private String uploadFileName;
    
  • Use FileUtils the commons-io package files are copied in the execute method.
    java FileUtils.copyFile(upload, new File("d:/upload",uploadFileName));

About 1.2 Struts2 file upload details:

  1. About the size of the file upload control
    • Defines the file upload file size default.properties
    • struts.multipart.maxSize = 2097152 upload files default total size of 2m
  2. The default is to use the commons-fileupload struts2 upload files. The following statement struts2 constant file, if pell, cos upload files, which must be introduced into the jar package.

    # struts.multipart.parser=cos
    # struts.multipart.parser=pell
    struts.multipart.parser=jakarta
  3. If problems occur, you need to configure input view, on the page by Display the error message problem: The information displayed on the page, all in English, in order to showcase Chinese and international

    #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}

      Be amended to

    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. Each upload file size control, and upload files on the type of control when multi-file upload.

    • Server-side: only need to declare the action attribute to List collection or array can be.
    private List<File> upload;
    private List<String> uploadContentType;
    private List<String> uploadFileName;
    • Browser:
    <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. How to control the size and type of the uploaded file for each uploaded file?

    • In fileupload interceptor, controlled by its properties.
    • maximumSize --- each upload file size
    • allowedTypes-- allowed to upload files mimeType type.
    • allowedExtensions-- allow the extension of the uploaded file.
    <interceptor-ref name="defaultStack">
        <param name="fileUpload.allowedExtensions">txt,mp3,doc</param>
    </interceptor-ref>

1.3 Example

jsp file

<%@ 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>

Class 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 file configuration

<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>

Second, download

2.1 file to download

  1. Hyperlinks
  2. Server code, write-back by the flow of the client.
    • By setting response response.setContentType(String mimetype);
    • By setting response response.setHeader("Content-disposition;filename=xxx");
    • By acquiring response flow, to download the information to write.

2.2 Struts2 file download

  • By <result type="stream">complete.

    <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
    
  • There are three classes StreamResult properties:

     protected String contentType = "text/plain"; //用于设置下载文件的mimeType类型
     protected String contentDisposition = "inline";//用于设置进行下载操作以及下载文件的名称
    protected InputStream inputStream; //用于读取要下载的文件。
  • The method defined in a class action

    public InputStream getInputStream() throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("d:/upload/" + filename);
    return fis;
    }
  • Configure 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>
  • Question 1: <a href="${pageContext.request.contextPath}/download?filename=捕获.png">捕获.png</a>Download error

  • Reason: The hyperlink is get requests, and download the file name is Chinese, garbled.

  • Question 2: When you download the capture file, the file name is a.txt, download the file extension is png, txt and we stipulate that in the configuration file?

    <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>
  • When download struts2, if you use It has flaws, such as: click to download, cancel the download, the server will generate an exception.

  • In development, Solution: You can download a plug-struts2 download operation, it solves the problem stream.

Sample Code

jsp file

<%@ 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>

Class 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 file configuration

<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>

Guess you like

Origin www.cnblogs.com/haoworld/p/struts2-wen-jian-shang-chuan-yu-xia-zai.html