脚本宝典收集整理的这篇文章主要介绍了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""""
脚本宝典总结
以上是脚本宝典为你收集整理的java实现浏览器下载文件,并解决兼容各浏览器的文件下载中文乱码全部内容,希望文章能够帮你解决java实现浏览器下载文件,并解决兼容各浏览器的文件下载中文乱码所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。