Struts2系列之文件上传下载

文件上传的必要条件

1. 表单的method 必须是post

2. 表单提供enctype必须是mulipart/from-data

3.提供input type=”file”类型上传输入域

注意:如果是大文件浏览器也会拦截不让上传

在struts2中文件上传是由fileUpload拦截器完成的

单文件上传:
jsp:

<head>
    <title>单文件上传</title>
</head>
<body>
<%--文件上传必要的条件--%>
<%--1, 要有一个表单 方式要是post请求--%>
<%--2, enctype="multipart/form-data--%>
<%--3, <input type="file" name="photo">--%>
<s:fielderror/>
<s:actionerror/>
<form action="${pageContext.request.contextPath}/upload.action" method="post" enctype="multipart/form-data">

    姓名:<input type="text" name="username">
    头像:<input type="file" name="photo">
    <input type="submit" value="上传">

</form>

action:

public class SingleUploadAction extends ActionSupport {

    private String username;
    private File photo;//必须是file类型,名字对应着表单的上传输入域
    private String photoFileName;//固定的写法:XXXFileName
    private String photoContentType;//上传文件的MIME类型,固定写法


    public  String upload() throws IOException {
        System.out.println(username + "fkdsjf");
        System.out.println(photoContentType);
        ServletContext servletContext = ServletActionContext.getServletContext();
        //获得存放文件的真是目录
        String directory = servletContext.getRealPath("/file");
        //构建目标文件
        File target = new File(directory,photoFileName);
        //写入目标文件
        FileUtils.copyFile(photo, target);
        return SUCCESS;
    }

    public String getUsername() {
        return username;
    }

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

    public File getPhoto() {
        return photo;
    }

    public void setPhoto(File photo) {
        this.photo = photo;
    }

    public String getPhotoFileName() {
        return photoFileName;
    }

    public void setPhotoFileName(String photoFileName) {
        this.photoFileName = photoFileName;
    }

    public String getPhotoContentType() {
        return photoContentType;
    }

    public void setPhotoContentType(String photoContentType) {
        this.photoContentType = photoContentType;
    }

}

struts.xml

  <!--修改文件的大小 (10M 1024*1024*10)-->
    <constant name="struts.multipart.maxSize" value="10485760"/>
    <!--由于我们在不被允许的格式中要显示用户可以看得懂的文字 可以写一个配置文件 constant name="国际化的一种方式"-->
    <constant name="struts.custom.i18n.resources" value="fileUploadMessage"/>

    <package name="p1" extends="struts-default">
        <action name="upload" class="com.wangyjie.struts.fileupload.SingleUploadAction" method="upload">
          <!--因为在默认的拦截器中  直接引用就可以了-->
           <interceptor-ref name="defaultStack">
               <!--限制文件后缀-->
               <param name="fileUpload.allowedExtensions">.jsp, png</param>
           </interceptor-ref>

            <result name="success">/success.jsp</result>
            <result name="input">/singleFileUpload.jsp</result>
        </action>
    </package>



文件下载

结果集类型的使用 stream

• 动作类的书写规范 : inputStream / fileName

•struts.xml中action result的type=“stream”两个参数:

◦ inputName[输入流的属性名]

◦ contentDisposition=attachment;filename=${fileName}[通知浏览器以下载形式打开]

action:

package com.wangyjie.struts.down;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.struts2.ServletActionContext;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * Created by dllo on 17/7/7.
 */
public class downLoadAction extends ActionSupport {

    //定义一个输入流
    private InputStream inputStream;
    private String imageFileName;

    public String getImageFileName() {

        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

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

    public String download() throws IOException {

        //实现下载.给inputStream赋值
        String realPath = ServletActionContext.getServletContext().getRealPath("/杰哥.jpg");
        //获取文件名
//        imageFileName = FilenameUtils.getName(realPath);
        imageFileName = filenameEncoding(FilenameUtils.getName(realPath), ServletActionContext.getRequest(),ServletActionContext.getResponse());
        inputStream = new FileInputStream(realPath);
//        FileUtils.getFile(realPath).getName();
        return SUCCESS;
    }

//中文处理
    public String filenameEncoding(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String agent = request.getHeader("User-Agent"); //获取浏览器的类型    System.out.println(agent);
        if (agent.contains("Firefox")) {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filename = "=?utf-8?B?"                + base64Encoder.encode(filename.getBytes("utf-8"))
                    + "?=";
        } else if(agent.contains("MSIE")) {
            filename = URLEncoder.encode(filename, "utf-8");
        } else if (agent.contains("Safari")){
            filename = new String(filename.getBytes("UTF-8"),"ISO8859-1");
        }else {
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

}

struts.xml

   <package name="downLoad" extends="struts-default">
       <action name="download" class="com.wangyjie.struts.down.downLoadAction" method="download">
           <result name="success" type="stream">
               <!--指定动作类中的输入流,属性名-->
               <param name="inputName">inputStream</param>
               <!--通知浏览器以下载的形式打开-->
               <!--文件名动态处理 添加 fileName 属性-->
               <param name="contentDisposition">attachment;filename=${imageFileName}</param>
           </result>
       </action>
   </package>

猜你喜欢

转载自blog.csdn.net/dapyandxpy/article/details/74836665