• java 解决火狐、谷歌、IE下载文件名乱码问题


    一.工具类

    package com.ahtcm.util;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.UnsupportedEncodingException;
    
    public class BrowserEncodeSwitchUtil {
    
        public static String getContentDisposition(String fileName, HttpServletRequest request) throws UnsupportedEncodingException {
            String content_disposition = "";
            String userAgent = request.getHeader("User-Agent");
            if (userAgent.contains("Safari")) {
                byte[] bytes = fileName.getBytes("UTF-8");
                fileName = new String(bytes, "ISO-8859-1");
                content_disposition = String.format("attachment; filename="%s"", fileName);
            } else {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                content_disposition = "attachment;filename=" + fileName;
            }
            return content_disposition;
        }
    }

    二.调用该方法

    @Override
        public void downloadExcelTpl(HttpServletRequest request, HttpServletResponse response) {
            FileInputStream is = null;
            try{
                String fileName = "居民病历导入模板.xls";
                String contentDisposition = BrowserEncodeSwitchUtil.getContentDisposition(fileName, request);
                response.setHeader("Content-Disposition", contentDisposition);
                /*获取文件的路径*/
                String realPath = request.getSession().getServletContext().getRealPath("/static/居民病历导入模板.xls");
                /*读取文件*/
                is=new FileInputStream(realPath);
                IOUtils.copy(is,response.getOutputStream());
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(is !=null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
  • 相关阅读:
    stanford nlp 3.8.0 parser输出的问题
    stanford nlp 3.8.0 parse中通过java程序获取root节点
    spring boot 项目中hanlp的配置(可增加自定义词典)
    springmvc jsonp 跨域调用的例子
    滚动字幕Marquee
    table-列组
    限时抢购-倒计时
    canvas基础绘制-绚丽时钟
    canvas基础绘制-绚丽倒计时
    JS进阶-闭包的几种常见形式
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/12585458.html
Copyright © 2020-2023  润新知