Loading

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();
                }
            }
        }
    }
复制代码

 

posted @   秋风飒飒吹  阅读(533)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示