欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Struts2 多文件上传、限制文件大小、更改错误提示--文件下载

程序员文章站 2022-07-14 08:16:16
...

好记性不如赖笔头…………

1、导入须要使用的jar包

Struts2 多文件上传、限制文件大小、更改错误提示--文件下载

2、创建jsp文件,代码如下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!--导入Struts2标签-->
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>文件上传</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  </head>

  <body>
  <h1>文件上传</h1>
    <s:form action="fileUpload.action" enctype="multipart/form-data">
        <s:file name="fileName" label="文件1"></s:file>
        <s:file name="fileName" label="文件2"></s:file> 
        <s:submit value="上传"></s:submit>
    </s:form>
    <hr/>
    <h1>文件下载</h1>
    <a href="${pageContext.request.contextPath }/fileDownload.action">下载图片</a>
  </body>
</html>

3、创建FileUploadAction类,并实现ActionSupport,具体代码如下:

package com.ckinghan.web.action;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {

    /**
     * 支持序列化
     */
    private static final long serialVersionUID = 1L;

    //上传文件数组
    private File[] fileName;

    //上传文件 的文件名
    private String[] fileNameFileName;

    //上传文件的MIME类型
    private String[] fileNameContentType;



    public File[] getFileName() {
        return fileName;
    }



    public void setFileName(File[] fileName) {
        this.fileName = fileName;
    }



    public String[] getFileNameFileName() {
        return fileNameFileName;
    }



    public void setFileNameFileName(String[] fileNameFileName) {
        this.fileNameFileName = fileNameFileName;
    }



    public String[] getFileNameContentType() {
        return fileNameContentType;
    }



    public void setFileNameContentType(String[] fileNameContentType) {
        this.fileNameContentType = fileNameContentType;
    }



    public String fileUpload(){
        //如果上传文件为空,则直接结束
        if(fileName == null || fileName.length == 0){
            return null;
        }
        //获取ServletContext 
        ServletContext context = ServletActionContext.getServletContext();
        //通过ServletContext 获取目录的真实路径,定位路径为:项目目录下,与WEB-INF同级,可以*更改
        String fileUrl = context.getRealPath("files");
        //创建文件,如果文件夹不存在,则创建
        File file = new File(fileUrl);
        if(!file.exists()){
            file.mkdirs();
        }

        //将文件复制到指定路径 下,会留下缓存文件,不建议使用
        /**
        try {
            for (int i = 0; i < fileName.length; i++) {
                FileUtils.copyFile(fileName[i],new File(file, UUID.randomUUID().toString()+fileNameFileName[i].substring(fileNameFileName[i].lastIndexOf("."), fileNameFileName[i].length())) );
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        */

        //将文件循环剪贴到指定位置并重命名,不会有缓存文件留下
        for(int i = 0; i <fileName.length;i++){
            fileName[i].renameTo(new File(file, UUID.randomUUID().toString()+fileNameFileName[i].substring(fileNameFileName[i].lastIndexOf("."), fileNameFileName[i].length())));
        }
        return null;
    }
}

4、创建文件下载 FileDownloadAction,继承ActionSupport类,具体内容如下:

package com.ckinghan.web.action;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileDownloadAction extends ActionSupport {

    //注意:此处命名不能使用in,会出问题
    private InputStream inputStream;

    private String fileName;

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public String fileDownload() throws FileNotFoundException{
        //获取图片路径
        String fileUrl = ServletActionContext.getServletContext().getRealPath("/files/33e765f4-cb37-4d3a-b9ae-b09240fc6519.jpg");
        //初始化流
        inputStream = new FileInputStream(fileUrl);

        fileName = "下载的相片.png";

        return SUCCESS;
    }
}

5、创建替换错误提示的FileUploadAction-messages.properties文件,与FileUploadAction文件处理于同一目录下,具体内容如下:

struts.messages.error.content.type.not.allowed=\u4E0A\u4F20\u6587\u4EF6\u4EC5\u652F\u6301\u56FE\u7247\u683C\u5F0F\:
struts.messages.error.file.extension.not.allowed=\u4EC5\u652F\u6301\u4EE5\u4E0B\u6269\u5C55\u540D\u6587\u4EF6\u7684\u4E0A\u4F20\uFF1Apng,jpeg,pjpeg,gif,bmp,jpg

效果图片如下:

Struts2 多文件上传、限制文件大小、更改错误提示--文件下载

此文件中替换内容的原始文件路径为:struts2-core-2.3.15.3.jar包下的org/apache/struts2/struts-messages.properties,文件的具体内容如下,可以参考将所有的错误替换为中文提示:

#
# $Id: struts-messages.properties 1379458 2012-08-31 14:06:00Z lukaszlenart $
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
struts.messages.invalid.token=The form has already been processed or no token was supplied, please try again.
struts.internal.invalid.token=Form token {0} does not match the session token {1}.

struts.messages.bypass.request=Bypassing {0}/{1}
struts.messages.current.file=File {0} {1} {2} {3}
struts.messages.invalid.file=Could not find a Filename for {0}. Verify that a valid file was submitted.
struts.messages.invalid.content.type=Could not find a Content-Type for {0}. Verify that a valid file was submitted.
struts.messages.removing.file=Removing file {0} {1}
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}

# dedicated messages used to handle various problems with file upload - check {@link JakartaMultiPartRequest#parse(HttpServletRequest, String)}
struts.messages.upload.error.SizeLimitExceededException=Request exceeded allowed size limit! Max size allowed is: {0} but request was: {1}!
struts.messages.upload.error.IOException=Error uploading: {0}!

devmode.notification=Developer Notification (set struts.devMode to false to disable this message):\n{0}

struts.exception.missing-package-action.with-context = There is no Action mapped for namespace [{0}] and action name [{1}] associated with context path [{2}].

6、创建Struts.xml配置文件在src目录下,具体配置信息如下 :

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <!-- 开启调试模式 -->
    <constant name="struts.devMode" value="true"/>
    <!-- 限制上传文件的大小,默认最大上传2M,这里改为了5M-->
    <constant name="struts.multipart.maxSize" value="5242880"/>
    <!-- 错误提示替换为中文,原配置文件路径为:struts2-core-2.3.15.3.jar/org/apache/struts2/struts-messages.properties -->
    <constant name="struts.custom.i18n.resources" value="com.ckinghan.web.action.FileUploadAction-messages"/>
    <!-- 开启OGNL的静态方法调用  -->
    <constant name="struts.ognl.allowStaticMethodAccess" value="true"/>

    <package name="fileUpload" extends="struts-default">
        <action name="fileUpload" class="com.ckinghan.web.action.FileUploadAction" method="fileUpload">
            <!-- 拦截器  -->
            <interceptor-ref name="defaultStack">
                <!-- 注入可以上传的文件类型 
                <param name="fileUpload.allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/jpg</param>-->
                <!-- 注入上传文件的扩展名-->
                <param name="fileUpload.allowedExtensions">.png,.jpeg,.pjpeg,.gif,.bmp,.jpg</param>

            </interceptor-ref>
            <result name="input" >/index.jsp</result>
        </action>

        <!-- 图片下载 -->
        <action name="fileDownload" class="com.ckinghan.web.action.FileDownloadAction" method="fileDownload">
            <!-- 返回的类型为stream流 ,下面注入参数的java类为:Struts2-core-2.3.15.3.jar包下的org.apache.struts2.dispatcher.StreamResult-->
            <result type="stream">
                <!-- 注入返回的表头:contentType =application/x-download  -->
                <param name="contentType">application/x-download</param>
                <!-- 注入参数contentDisposition,返回的类型为附件下载,使用OGNL将程序给定的文件名写入命名给图片,使用URLEncoder防止中文乱码 -->
                <param name="contentDisposition">attachment;filename=${@aaa@qq.com(fileName,"UTF-8")}</param>
                <!-- 将指定的动作类中的inputStream注入到inputName中,实现下载 -->
                <param name="inputName">inputStream</param>
            </result>
        </action>
    </package>

</struts>

配置完成,将项目启动,访问效果如下 :

Struts2 多文件上传、限制文件大小、更改错误提示--文件下载

上传两张图片效果如下:

Struts2 多文件上传、限制文件大小、更改错误提示--文件下载

测试其它类型的文件上传提示,效果如下 :

Struts2 多文件上传、限制文件大小、更改错误提示--文件下载

如果文件上传的大小超过了5M,会直接返回到上传页面。

访问下载效果图:

Struts2 多文件上传、限制文件大小、更改错误提示--文件下载

注意:下载的前提是,在项目目录下,有files文件夹,并有33e765f4-cb37-4d3a-b9ae-b09240fc6519.jpg图片,否则会报找不到文件错误