您的位置:首页 > 编程语言 > Java开发

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

2017-10-19 14:40 711 查看
场景描述:

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

浏览器下载代码如下:

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: