文件上传与下载(四)Struts2 实现

这一部分使用Struts2实现文件的上传与下载。

必须条件:
前台form表单<code>method="post" enctype="multipart/form-data"</code>

Struts2在原有的上传解析器继承上做了进一步封装,更进一步简化了文件上传。

Struts2默认使用的是Common-FileUpload的文件上传框架,因此,如果需要使用Struts2的文件上传功能,需要在web应用中导入相应的jar包。

Action需要使用三个属性来封装该文件域的信息:

  1. 类型为File的xxx属性封装了该文件域对应的文件的文件内容。

  2. 类型为String的xxxFileName属性封装了该文件域对应的文件的文件名称。

  3. 类型为String的xxxContentType属性封装了该文件域对应的文件的文件类型。

关键:
struts.xml配置拦截器,设置允许上传类型、文件大小等信息。


上传单个文件

web.xml

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

前台页面:

        <h2>Struts2上传</h2>
        <s:form action="doUpload.action" method="post" enctype="multipart/form-data">
            <s:file name="upload" label="File"/>
            <s:submit value="上传"/>${strutsResult}
        </s:form>

在jsp页面中增加Struts2的标签库。

<%@ taglib uri="/struts-tags" prefix="s"%>  

编写UploadAction

public class UploadAction extends ActionSupport {
    
    //文件内容(要与前台的name属性值一致)
    private File upload;
    //文件类型
    private String uploadContentType;
    //文件名称
    private String uploadFileName;
    //返回消息提示
    private String strutsResult;
    
    
    public File getUpload() {
        return upload;
    }


    public void setUpload(File upload) {
        this.upload = upload;
    }


    public String getUploadContentType() {
        return uploadContentType;
    }


    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }



    public String getUploadFileName() {
        return uploadFileName;
    }


    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }


    public String getStrutsResult() {
        return strutsResult;
    }


    public void setStrutsResult(String strutsResult) {
        this.strutsResult = strutsResult;
    }


    public String execute() throws IOException {
        //获取服务器上传文件存放路径
        String path = ServletActionContext.getServletContext().getRealPath("/upload");
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        FileUtils.copyFile(upload, new File(file, uploadFileName));
        strutsResult = "上传成功";
        
        return SUCCESS;
    }
}

上面的三个基本属性封装重要的信息。

接下来来配置struts.xml

<?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.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">

        <action name="doUpload" class="com.meng.action.UploadAction">
            <result name="success">/index.jsp</result>
            <!-- 配置拦截器限制上传文件类型及大小 -->
            <interceptor-ref name="fileUpload">
                <param name="allowedType">image/bmp,image/x-png,image/gif,image/jpeg</param>
                <param name="maximumSize">2M</param>
            </interceptor-ref>
            <interceptor-ref name="basicStack"></interceptor-ref>
        </action>
    </package>

</struts>

多文件上传(批量上传)

修改前台页面

    <h2>上传多个文件</h2>
    <s:form action="doUpload.action" method="post" enctype="multipart/form-data">
        <s:file name="upload" label="File"/>
        <s:file name="upload" label="File"/>
        <s:file name="upload" label="File"/>
        <s:submit value="上传"/>${strutsResult}
    </s:form>   

UploadAction

public class UploadAction extends ActionSupport {

    // 文件内容
    private List<File> upload;
    // 文件类型
    private List<String> uploadContentType;
    // 文件名称
    private List<String> uploadFileName;
    // 返回消息提示
    private String strutsResult;

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

    public String getStrutsResult() {
        return strutsResult;
    }

    public void setStrutsResult(String strutsResult) {
        this.strutsResult = strutsResult;
    }

    public String execute() throws IOException {
        // 获取服务器上传文件存放路径
        String path = ServletActionContext.getServletContext().getRealPath("/upload");
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        for (int i = 0; i < upload.size(); i++) {
            FileUtils.copyFile(upload.get(i), new File(file, uploadFileName.get(i)));
        }
        strutsResult = "上传成功";

        return SUCCESS;
    }

}

这样就能成功的完成上传的功能。


文件的下载

通常情况下,我们在下载文件的时候,文件的路径都是股固定的。

所以实现起来也是比较简单的。

在前台给定一个连接

<h2>Struts2下载</h2>
<a href="doDownload.action">下载</a>

然后配置struts.xml,添加如下配置:

<action name="doDownload" class="com.meng.action.download.DownloadAction">
    <param name="inputPath">/upload/10.jpg</param>
    <result name="success" type="stream">
        <param name="contentType">application/octet-stream</param>
        <param name="inputName">inputStream</param>
        <param name="contentDisposition">attachment;filename="10.jpg"</param>
        <param name="bufferSize">8192</param>
    </result>
 </action>  

编写DownloadAction

public class DownloadAction extends ActionSupport {
    
    private String inputPath;

    public String getInputPath() {
        return inputPath;
    }

    public void setInputPath(String inputPath) {
        this.inputPath = inputPath;
    }

    @Override
    public String execute() throws Exception {
        
        return SUCCESS;
    }
    
    public InputStream getInputStream() {
        
        return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
        
    }
}

当我们点击连接的时候,就会下载我们所给定的文件。

但是这样配置很是不方便,我们可以通过URL来给定所要下载的文件名称。

将上面的代码进行修改:

<a href="doDownload.action?filename=10.jpg">下载</a>
<action name="doDownload" class="com.meng.action.download.DownloadAction">
    <result name="success" type="stream">
        <param name="contentType">application/octet-stream</param>
        <param name="inputName">inputStream</param>
        <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
        <param name="bufferSize">8192</param>
    </result>
 </action>  
public class DownloadAction extends ActionSupport {
    
    private String filename;
    
    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }
    
    public InputStream getInputStream() throws IOException {
        
        String path = ServletActionContext.getServletContext().getRealPath("/upload");
        String filepath = path + "\\" + filename;
        File file = new File(filepath);
        return FileUtils.openInputStream(file);
    }
    
    public String getDownloadFileName() {
        String downloadFileName = "";
        try {
            // 转换下中文的文件名的的编码
            downloadFileName = URLEncoder.encode("文件下载.jpg", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return downloadFileName;
    }
}

这样配置是不是用起来的时候会方便的多。

推荐阅读更多精彩内容