admin管理员组文章数量:1533913
场景描述:
由于项目需求,需要支持浏览器下载文件,比如招聘网站的在线简历下载。
浏览器下载代码如下:
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.URLEncoder.encode(fileName, "UTF-8");
content_disposition = "attachment;filename=" + fileName;
}
return content_disposition;
}
}
版权声明:本文标题:java实现浏览器下载文件,并解决兼容各浏览器的文件下载中文乱码 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1726114109a1055922.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论