j2ee之struts2文件下载

1、文件上传

首先要导入要用到的struts2的jar包

2、在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>
复制代码

3、在src目录下配置struts.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
          "http://struts.apache.org/dtds/struts-2.0.dtd">

<!-- START SNIPPET: xworkSample -->
<struts>
    <include file="/constant.xml"></include>
</struts>

<!-- END SNIPPET: xworkSample -->

4、写一个查询指定目录的文件列表的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>文件下载</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>
      <table align="center" border="1" cellpadding="3" cellspacing="0">
          <%@taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>
              <tr>
                  <th>序号</th>
                  <th>文件名</th>
                  <th>下载</th>
              </tr>
          <c:forEach var="list" items="${requestScope.files}" varStatus="statu">
              <tr>
              <td>${statu.count }</td>
              <td>${list }</td>
              <c:url value="downFileAction_downFile" var="url">
                  <c:param name="fileName" value="${list}"></c:param>
              </c:url>
              <td>
                <a href="${url}">下载</a>
              </td>
              </tr>    
          </c:forEach>
      </table>
  </body>
</html>

5、写一个action用于向jsp页面传入文件列表,以及提供struts2文件下载所需要的输入流和文件名

package com.xinzhi.file;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileDownAction extends ActionSupport {

    // 这段代码的主要功能是传入文件List
    public String down() throws Exception {
        String realPath = ServletActionContext.getServletContext().getRealPath(
                "/load");
        File file = new File(realPath);
        String[] list = file.list();
        Map<String, Object> request = ActionContext.getContext()
                .getContextMap();
        request.put("files", list);
        return "success";
    }

    /*
     * 以下代码的主要功能是进行文件的下载
     */
    private String fileName;

    public void setFileName(String fileName) {
        try {
            // 因为链接是通过get方式提交,为了防止乱码
            fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.fileName = fileName;
    }

    public String downFile() throws Exception {
        // 指定一个方法
        return "download";
    }

    public InputStream getAttrInputStream() {
        // 传入一个所需要的输入流
        return ServletActionContext.getServletContext().getResourceAsStream(
                "/load/" + fileName);
    }

    public String getDownFileName() {
        try {
            // 规范链接格式
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return fileName;
    }
}

6、当前包下创建一个struts2文件下载配置文件

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
          "http://struts.apache.org/dtds/struts-2.0.dtd">

<!-- START SNIPPET: xworkSample -->
<struts>
    <package name="inputpackage" extends="struts-default" >
       <action name="downFileAction_*" class="com.xinzhi.file.FileDownAction" method="{1}">
           <result name="success">/down.jsp</result> 
           <result name="download" type="stream"><!--
           八进制流-octet八进制
               --><param name="contentType">application/octet-stream</param>
               <param name="inputName">attrInputStream</param><!--
               文本部署-disposition部署 -附件attachement
               --><param name="contentDisposition">attachment;filename=${downFileName}</param>
               <param name="bufferSize">1024</param>
           </result>
       </action>
    </package>
</struts>

7、至此文件下载就完成了

原文地址:https://www.cnblogs.com/ShaoXin/p/6999342.html