1.废话不多说,直接上一段上传的代码
@GetMapping(value = "/api/file/downloadFile")
@ResponseBody
public void getUrlDownload(String url, HttpServletResponse response) {
File file = new File(url);
// 后缀名
//判断文件是否存在如果不存在就进行异常处理
if (!(file.exists() && file.canRead())) {
System.out.println("文件不存在");
}
String fileName = url.substring(url.lastIndexOf(File.separator)+1);
fileName = VisualUtils.transUrlChinese(fileName);
try (
FileInputStream inputStream = new FileInputStream(file);
OutputStream stream = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
) {
byte[] buffer = new byte[4096];
//通过设置头信息给文件命名,也即是,在前端,文件流被接受完还原成原文件的时候会以你传递的文件名来命名
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment; filename* = UTF-8''" + fileName);
int length = bis.read(buffer);
while (length != -1) {
stream.write(buffer, 0, length);
length = bis.read(buffer);
}
stream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
解释上面的关键点 public static String transUrlChinese(String str) {
String resultURL = "";
try {
for (int i = 0; i < str.length(); i++) {
char charAt = str.charAt(i);
//只对汉字处理
if (isChineseChar(charAt)) {
String encode = URLEncoder.encode(charAt + "", "UTF-8");
resultURL += encode;
} else {
resultURL += charAt;
}
}
} catch (UnsupportedEncodingException e) {
log.warn("解码异常!");
}
return resultURL;
}
private static boolean isChineseChar(char c) {
return String.valueOf(c).matches("[\u4e00-\u9fa5]");
}
2.3 设置文件头
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment; filename* = UTF-8''" + fileName);
特别注意 "attachment; filename* = UTF-8’’"这个设置,它可以将文件编码转为url编码,比如中文特殊字符”【、- “ 等等,但是不能把汉字转为URL编码,所以结合步骤2.2,就可以完美的解决文件名乱码问题;
2.4 一般的文件名转为URL编码的逻辑,不能处理特殊字符