本文主要是介绍Safari浏览器下载文件时,文件名会URL encoded,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题:相同链接下载文件,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/图片.jpgClassPathResource 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
这篇关于Safari浏览器下载文件时,文件名会URL encoded的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!