前言
上传文件时,文件服务器会给文件重新生成一个一串英文字符的名称,导致前端使用a标签下载这个文件时,文件内容是原来的内容,但是下载的文件名是一串英文字符,很不好的用户体验。而且download也不是太好用
比如:上传的是原文件名是 “组织架构2019.pdf”
<a href="http://url/16/B9/rBADs1ytTmCASKrBAAL7byPiPRU439.pdf" download="组织架构2019.pdf" target="_blank">下载</a>
给下载的文件重命名
废话不多说上代码
/**
*
* @param request
* @param fileUrl 下载路径
* @param fileName 文件名
* @param response
* @throws Exception
*/
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void downloadAction(HttpServletRequest request, String fileUrl,String fileName,HttpServletResponse response) throws Exception {
if (StringUtils.isBlank(fileUrl)) {
throw new Exception("文件fileUrl为空");
}
if (StringUtils.isBlank(fileName)) {
throw new Exception("文件fileName为空");
}
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
String downloadName = null;
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
//println "IE浏览器"
downloadName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
response.setHeader("Content-Disposition", "attachment;fileName=" + downloadName);
} else {
//println "其他浏览器"
downloadName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");//其他浏览器
response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");
}
URL url = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3 * 10000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
OutputStream os = response.getOutputStream();
try {
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
os.close();
inputStream.close();
conn.disconnect();
}
}