使用场景:前端使用window.open(url)下载文件,但是浏览器能识别此文件,会打开。不能识别的走下载,于是写代码所有文件都走下载功能
// 对url编码,防止携带特殊字符&,导致获取url不完整
window.open('/download/file?fileName=HelloWorld&fileUrl=' + encodeURIComponent(fileUrl));
import org.springframework.util.FileCopyUtils;
@GetMapping("/download/file")
public void downloadFile(String fileUrl, String fileName,HttpServletResponse response) {
try {
URL url = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
InputStream inputStream = conn.getInputStream();
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "application/force-download");
response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
FileCopyUtils.copy(inputStream,response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}