zoukankan      html  css  js  c++  java
  • 如何在struts2中实现下载?

    <a href="${pageContext.request.contextPath}/download?filename="+filename>点击下载</a>

    在action类中执行完execute方法后返回成功字符串跳转到result之后再result中设置contentType、contentDisposition、inputStream

    <result name="success" type="stream">
      <param name="contentType">${contentType}</param>
      <param name="contentDisposition">attchment;filename=${downloadFileName}</param>
      <param name="inputStream">${inputStream}</param>
    </result>

    在action类中提供对应的getContentType、getDownloadFileName、getInputStream方法

    
    

    public String getContentType() {

      String mimeType = ServletActionContext.getServletContext().getMimeType(filename);
      return mimeType;

    }

    public String getDownloadFileName() throws UnsupportedEncodingException {

      return DownloadUtils.getDownloadFileName(ServletActionContext.getRequest().getHeader("user-agent"), filename);

    }

    public InputStream getInputStream() throws FileNotFoundException,UnsupportedEncodingException {

      filename = new String(filename.getBytes("iso8859-1"), "utf-8"); // 解决中文名称乱码.

      FileInputStream fis = new FileInputStream("d:/upload/" + filename);
      return fis;
    }

     

    用DownloadUtils工具类来返回一个下载文件名,目的之为了去支持不同的浏览器,比如火狐用的是BASE64编码

    public class DownloadUtils {
    
        public static String getDownloadFileName(String agent,String filename) throws UnsupportedEncodingException{
            if(agent.contains("MSIE")){
                //IE
                filename = URLEncoder.encode(filename,"utf-8");
            }else if(agent.contains("Firefox")){
                //火狐浏览器
                BASE64Encoder base64Encoder = new BASE64Encoder();
                filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
            }else{
                //其他浏览器
                filename = URLEncoder.encode(filename,"utf-8");
            }
            return filename;
        }
        
    }
  • 相关阅读:
    Hbase的数据目录更换后server is not running yet报错
    挂载新加4T硬盘到home目录
    Hadoop(二)--Hadoop运行模式
    Hadoop(一)--Hadoop框架介绍
    KubeSphere(四)--Devops工程pipeline
    KubeSphere(三)--示例:安装wordpress到k8s
    KubeSphere(二)--多租户管理权限控制
    KubeSphere(一)--基于k8s安装KubeSphere
    com.alibaba.fastjson.JSON.toJSONString使用时值为NULL的属性被忽略的问题
    数据库命令-实战
  • 原文地址:https://www.cnblogs.com/zyh1994/p/5401548.html
Copyright © 2011-2022 走看看