问题:相同链接下载文件,safari文件名编码异常
解决:
response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + URLEncoder.encode(filename, "UTF-8"));
问题描述
-
谷歌下载(正常)
-
Safari下载(异常)
问题代码示例
@RestController
@RequestMapping("/file")
public class FileController {
@GetMapping("/download")
public void download(HttpServletResponse response) {
String filename = "图片.jpg";
String path = "img/" + filename;
ClassPathResource classPathResource = new ClassPathResource(path);
try (FileInputStream fis = new FileInputStream(classPathResource.getFile());
ServletOutputStream sos = response.getOutputStream()) {
//设置响应头
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
IOUtils.copy(fis, sos);
} catch (Exception e) {
throw new RuntimeException("下载失败!");
}
}
}
问题解决如下
@RestController
@RequestMapping("/file")
public class FileController {
@GetMapping("/download")
public void download(HttpServletResponse response) {
String filename = "图片.jpg";
String path = "img/" + filename; // resources下路径,比如文件位置在:resources/img/图片.jpg
ClassPathResource classPathResource = new ClassPathResource(path);
try (FileInputStream fis = new FileInputStream(classPathResource.getFile());
ServletOutputStream sos = response.getOutputStream()) {
//设置响应头
response.setHeader("Content-Disposition", "attachment;filename*=utf-8''"
+ URLEncoder.encode(filename, "UTF-8"));
IOUtils.copy(fis, sos);
} catch (Exception e) {
throw new RuntimeException("下载失败!");
}
}
}
关键代码
response.setHeader("Content-Disposition", "attachment;filename*=utf-8''"
+ URLEncoder.encode(filename, "UTF-8"));
下载后文件名正常
文章参考
Safari浏览器下载文件时,文件名会URL encoded