struts2文件上传和下载

struts2已经有包装好的文件上传下载组件,非常方便。看源代码,红色标记的就是文件上传的拦截器
这里写图片描述

接下来我们再来看看这个拦截器的源码,下面标记的三个参数,仔细看注释,
这里写图片描述

但是配置文件并不包括配置画红线的那两个参数,继续看源码注释的例子:
这里写图片描述
看到下划线标记红色的三个参数了吗?那三个才是可以用配置文件注入的属性。
分别是:maximumSize、allowedTypes 和 allowedExtensions

文件下载的话,我们只要按照二进制流输出就行,struts2也有包装好的返回类型给我们使用,看源码
这里写图片描述

源码中有好几个参数,我们只要设置三个参数就可以了,分别是contentType、contentDisposition和inputStream
这里写图片描述

好了源码就分析到这,下面开始实现:
静态页面:

<%@ page language="Java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE HTML>
<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> 
<!-- <s:form/>默认是post -->  
<s:form action="/upload/upload" enctype="multipart/form-data">
    <s:textfield name="username" label="username"></s:textfield>
    <s:file name="file" label="file"></s:file>
    <s:submit value="submit"></s:submit>
</s:form>
<hr>
<a href="${pageContext.request.contextPath }/upload/download">下载</a>
</body>
</html>

action类:

package cn.jieou.struts.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
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 String username;
    private File file;//上传的文件
    private String fileFileName;//上传文件的名字
    private String fileContentType;//上传组件MIME类型
    private String fileName;//下载的文件名
    private InputStream inputStream;//输入流
    public String upload(){
        /**
        * 这里指定一个相对路径,但实际开发中都会指定一个绝对路径来存放文件,
        * 绝对路径可以在配置文件中存放,便于修改,以防重新部署项目时文件丢失。
        */
        String dir = ServletActionContext.getServletContext().getRealPath("/WEB-INF/files");
        File newfile = new File(dir);
        if(!newfile.exists()){
            newfile.mkdirs();
        }else {
                try {
                    //把文件复制的指定目录下
                    FileUtils.copyFile(file, new File(newfile, fileFileName));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        return SUCCESS;
    }

    public String download(){
        String filepath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/files");
        File downloadfile = new File(filepath,"图像 2.png");
        try {
            inputStream = new FileInputStream(downloadfile);
            fileName = "MJ.png";
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "download";
    }

    public String getFileName() {
        return fileName;
    }

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

    public InputStream getInputStream() {
        return inputStream;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }
}

配置文件:

<?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>
    <package name="cn.jieou.struts.action.FileUploadAction" 
        extends="struts-default" namespace="/upload">
        <action name="upload" class="cn.jieou.struts.action.FileUploadAction"  method="upload">
            <interceptor-ref name="defaultStack">
                <!-- 允许上传文件最大值;单位字节 -->
                <param name="fileUpload.maximumSize">1048576</param>
                <!-- 允许上传文件的MIME类型;这里指定允许图片的所有类型 -->
                <param name="fileUpload.allowedTypes">image/*</param>
                <!-- 允许上传文件的拓展名;这里指定jpg,png和gif-->
                <param name="fileUpload.allowedExtensions">jpg,png,gif</param>
            </interceptor-ref>
            <result name="success">/success.jsp</result>
            <result name="input">/upload.jsp</result>
        </action>
        <action name="download" class="cn.jieou.struts.action.FileUploadAction"  method="download">
            <result name="download" type="stream">
                <!-- action中的输入流名字 -->
                <param name="inputStream">inputStream</param>
                <!-- 重写请求头;这里最好不要写死,接收action -->
                <param name="contentDisposition">attachment;filename=${fileName}</param>
                <!-- 设置响应头中的MIME类型 -->
                <param name="contentType">application/octet-stream</param>
            </result>
        </action>
    </package>
</struts>

说明:有时候xml配置文件配置1048576未必会生效,最好可以在struts.properties文件配置struts.multipart.maxSize=1048576,效果是一样,当然配置一种就行,建议使用后面properties配置,是全局配置。

多文件上传
只需要在后台用数组接收即可,例如:
这里写图片描述
然后在循环数组复制文件到指定位置。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超级奶爸MJCX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值