springboot文件流的方式下载文件(包含中文名乱码解决)
解决springboot 中文名文件下载
·
项目需要用到文件下载功能,试了很多方式,在下载的时候response返回都会报错,后面找到了解决方法,源码如下:
public void download(String url, HttpServletResponse httpServletResponse) {
String filePath = String.format("%s/%s", System.getProperty("user.dir"), url);
File file = new File(filePath);
httpServletResponse.setHeader("content-type", "application/octet-stream;charset=utf-8");
httpServletResponse.setContentType("application/octet-stream");
try {
httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = httpServletResponse.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
更多推荐
所有评论(0)