• java struts2 的 文件下载


    jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>

      <a href="download.do">点击下载</a>

    </body>
    </html>

    struts.xml

    <!-- 下载文件 -->
    <action name="download" class="com.hdsx.gzgispf.controller.FileDownloadAction">
      <result name="success" type="stream">
      <param name="contentType">text/plain</param>
      <param name="inputName">inputStream</param>
      <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
      <param name="bufferSize">4096</param>
      </result>
    </action>

    com.hdsx.gzgispf.controller.FileDownloadAction  :

    /**
    * 处理带中文的文件名(可设置下载文件名)
    * @return
    */
    public String getDownloadFileName() {
    fileName="struts2的下载文件.doc";
    String downloadFileName = null;
    try {
    downloadFileName = fileName;
    downloadFileName = URLEncoder.encode(downloadFileName,"UTF-8");
    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    }
    return downloadFileName;
    }

    /**
    * 获取下载流
    * @return
    */
    public InputStream getInputStream () {

    String context="";
    String str="";
    InputStream in=null;

    //获取当前项目的路径    被下载的文件名为:111.doc
    String path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/")+"111.doc";


    try {
    File someFile = new File(path );
    FileInputStream fis = new FileInputStream(someFile);
    InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
    BufferedReader br = new BufferedReader(isr);

    while((str=br.readLine())!=null){
    context+=str+" ";
    }
    in=new ByteArrayInputStream(context.getBytes());
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return in ;

    }

    public String execute(){
    return "success";
    }

  • 相关阅读:
    码到成功——冲刺随笔 day 8
    码到成功——冲刺随笔 day 7
    码到成功——冲刺随笔 day 6
    码到成功——冲刺随笔 day 5
    码到成功——冲刺随笔 day 4
    码到成功——冲刺随笔 day 3
    码到成功——冲刺随笔 day 2
    Alpha冲刺 —— 5.9
    Alpha冲刺 —— 5.8
    Alpha冲刺 —— 5.7
  • 原文地址:https://www.cnblogs.com/ssrsblogs/p/struts2_fileDownLoad.html
Copyright © 2020-2023  润新知