java实现浏览器下载文件,并解决兼容各浏览器的文件下载中文乱码

场景描述:
由于项目需求,需要支持浏览器下载文件,比如招聘网站的在线简历下载。

浏览器下载代码如下:

public static void downloadFile(File file, HttpServletResponse response) {
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
              fin = new FileInputStream(file);
              out = response.getOutputStream;
              response.setCharacterEncoding("utf-8");
              response.setContentType("application/x-download");
              response.addHeader("Content-Disposition", "attachment;filename=resume.doc");

              byte[] buffer = new byte[1024];
              int bytesToRead = -1;
              // 通过循环将读入的Word文件的内容输出到浏览器中
              while((bytesToRead = fin.read(buffer)) != -1) {
                   out.write(buffer, 0, bytesToRead);
               }
           } catch (Exception e) {
              e.printStackTrace();
           } finally {
              if(fin != null) fin.close();
              if(out != null) out.close();

        }
    }

如果文件名为中文,上面的代码下载的文件名会乱码。

解决中文乱码方法:
拿到浏览器请求的usreAgent,判断是否包含MSIE,是则直接讲文件名转换为bytes,否则使用UTF-8转换。
然后将bytes使用ISO-8859-1编码转换为字符串,返回到浏览器。

代码如下:

public class DownloadServlet extends HttpServlet {  
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        // codes..  
        String name = "中文名 带空格 的测试文件.txt";  
        String userAgent = request.getHeader("User-Agent"); 
        // name.getBytes("UTF-8")处理safari的乱码问题 
        byte[] bytes = userAgent.contains("MSIE") ? name.getBytes() : name.getBytes("UTF-8");                     
        // 各浏览器基本都支持ISO编码
        name = new String(bytes, "ISO-8859-1");  
        // 文件名外的双引号处理firefox的空格截断问题 
        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", name));   
        // codes..  
    }  
}

附个人封装的工具类:

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

public class BrowerEncodeingSwitch {
    /**
     * 根据不同浏览器 User-Agent,生成不同的 Content_disposition
     * @param fileName
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getContentDisposition(String fileName, HttpServletRequest request) throws UnsupportedEncodingException {
        String content_disposition = "";
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("Safari")) {
            // name.getBytes("UTF-8")处理safari的乱码问题
            byte[] bytes = fileName.getBytes("UTF-8");
            // 各浏览器基本都支持ISO编码
            fileName = new String(bytes, "ISO-8859-1");
            // 文件名外的双引号处理firefox的空格截断问题
            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;
    }
}
  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值