七 Struts2 文件上传和下载

  配置文件

<?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="my" namespace="/" extends="struts-default">
     <!-- 文件上传 -->
        <action name="upload" class="com.action.UploadAction">
            <result name="success">/jsp/fileupload.jsp</result>
        </action>
<!-- 文件下载 --> <action name="download" class="com.action.DownAction"> <result name="success" type="stream"> <!-- inputNamec参数对应action中的getFileDownload方法,参数的值就是此方法去掉get前缀、首字母小写的字符串 --> <param name="inputName">fileDownload</param> <!-- 下载缓冲区的大小 --> <param name="bufferSize">1024</param> </result> </action> </package> </struts>

文件上传:

  fileupload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>My JSP 'fileupload.jsp' starting page</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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
   <form action="upload" method="post" enctype="multipart/form-data">
           <input type="file" name="file"><br>
           <input name="miaoshu"><br>
        <input type="submit" value="提交">
   </form>
  </body>
</html>

  UploadAction.java

package com.action;

import java.io.*;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport{
    String miaoshu;
    File file;
    String fileFileName;//获取文件名,该属性名的组成为file+FileName  后面是固定写法
    String fileContentType;//获取文件类型
    public String getMiaoshu() {
        return miaoshu;
    }
    public void setMiaoshu(String miaoshu) {
        this.miaoshu = miaoshu;
    }
    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;
    }
    
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        System.out.println(miaoshu);
        //获取文件存储路径
        String path = ServletActionContext.getServletContext().getRealPath("/upload");
        //输出流
        OutputStream os = new FileOutputStream(new File(path,fileFileName));
        //输入流
        InputStream is = new FileInputStream(file);
        byte[] buf = new byte[1024];
        int length = 0 ;
        while(-1 != (length = is.read(buf) ) )
        {
            os.write(buf, 0, length) ;
        }
        is.close();
        os.flush();
        os.close();
        return SUCCESS;
    }
}

文件下载:

  filedownload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>My JSP 'filedownload.jsp' starting page</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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <form action="download" method="post">
        输入文件名:<input name="filename"><br/>
        <input type="submit" value="下载">
    </form>
    <p><a href="javascript:window.location='download?filename='+encodeURI('李四.png')">李四下载</a></p>
  </body>
</html>

  DownAction.java

package com.action;



import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownAction extends ActionSupport{
    String filename;

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }
    
    public InputStream getFileDownload(){
        try {
            //设置下载的头部信息,包括文件名等等
            ServletActionContext.getResponse().setHeader("Content-Disposition",
                    "attachment;fileName=" + URLEncoder.encode(filename, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ServletActionContext.getServletContext().getResourceAsStream("upload/"+filename);
    }
    
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        return SUCCESS;
    }
}

附:文件批量上传

  filesupload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>My JSP 'filesupload.jsp' starting page</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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  <script type="text/javascript">
      function add(){
          var input = document.createElement("input");
          input.setAttribute("type","file");
          input.setAttribute("name","file");
          
          document.getElementById("files").appendChild(input);
      }
  </script>
  <body>
    <form action="uploads" method="post" enctype="multipart/form-data">
        <div id="files">
            <input type="file" name="file" />
        </div>
        <input type="button" value="添加" onclick="add()">
        <input type="submit" value="提交">
    </form>
  </body>
</html>

  UploadsAction.java

package com.upload.action;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadsAction extends ActionSupport{
    List<File> file;
    List<String> fileFileName;
    List<String> fileContentType;
    public List<File> getFile() {
        return file;
    }
    public void setFile(List<File> file) {
        this.file = file;
    }
    public List<String> getFileFileName() {
        return fileFileName;
    }
    public void setFileFileName(List<String> fileFileName) {
        this.fileFileName = fileFileName;
    }
    public List<String> getFileContentType() {
        return fileContentType;
    }
    public void setFileContentType(List<String> fileContentType) {
        this.fileContentType = fileContentType;
    }
    
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        //获取文件存储路径
        String path = ServletActionContext.getServletContext().getRealPath("/upload");
        for(int i=0;i<file.size();i++){
            //输出流
            OutputStream os = new FileOutputStream(new File(path,fileFileName.get(i)));
            //输入流
            InputStream is = new FileInputStream(file.get(i));
            byte[] buf = new byte[1024];
            int length = 0 ;
            while(-1 != (length = is.read(buf) ) )
            {
                os.write(buf, 0, length) ;
            }
            is.close();
            os.flush();
            os.close();
        }
        
        addActionMessage("成功");
        return SUCCESS;
    }
}
原文地址:https://www.cnblogs.com/wlxslsb/p/10788837.html