解决浏览器下载附件乱码问题 IE11

本文介绍了一种解决浏览器下载附件时出现乱码问题的方法,针对不同浏览器(Firefox、Chrome、IE7+)提供了相应的编码解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 /**
    * @Title:encodeChineseDownloadFileName
    * @Description TODO(解决浏览器下载附件乱码问题). 
    * @date  2016年8月19日 
    * @author lzqiangPC  
    * @param pFileName
    * @return
    * @throws Exception
     */
    private static String encodeChineseDownloadFileName( String pFileName) throws Exception {  
     	String filename = null;    
        String agent = SpringContextUtil.getHttpServletRequest().getHeader("USER-AGENT");    
        if (null != agent){    
            if (-1 != agent.indexOf("Firefox")) {//Firefox    
                filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8"))))+ "?=";    
            }else if (-1 != agent.indexOf("Chrome")) {//Chrome    
                filename = new String(pFileName.getBytes(), "ISO8859-1");    
            } else {//IE7+    
                filename = java.net.URLEncoder.encode(pFileName, "UTF-8");    
                filename = StringUtils.replace(filename, "+", "%20");//替换空格    
            }    
        } else {    
            filename = pFileName;    
        }    
        return filename;   
    }  

    /**
     * 附件下载
     * 
     * @param filename
     *            文件名
     * @param path
     *            文件路径
     * @param response
     */
    public static void download(String filename, String path,
            HttpServletResponse response) {
        InputStream in = null;
        OutputStream os = null;
        try {
        	filename = encodeChineseDownloadFileName(filename);
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename="+filename);
            File file = new File(path);
            if (file.exists()) {
                in = new FileInputStream(path);
                os = response.getOutputStream();
                byte[] b = new byte[1024 * 1024];
                int length;
                while ((length = in.read(b)) > 0) {
                    os.write(b, 0, length);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值