大家好,又见面了,我是你们的朋友全栈君。
一、前台通过a标签打开接口,传入文件id
<a href="/cdc/announcement/downloadFile/1">下载</a>
二、后台接收id,查找对应文件,进行下载
@RequestMapping(value = "downloadFile/{id}", method = RequestMethod.GET)
@PreAuthorize("hasAuthority('view')")
@ResponseBody
public void downloadFile(HttpServletRequest req, HttpServletResponse resp, @PathVariable("id") Long id) {
AnnouncementAnnex announcementAnnex = announcementAnnexService.selectById(id);
//真实文件名
String name = announcementAnnex.getAnnexUrl();
String downloadName=announcementAnnex.getAnnexName();
// 进行转码后的文件名,用来下载之后的文件名
PublicController.download(resp,name,downloadName);
}
其中download方法
/**
* @param resp
* @param name 文件真实名字
* @param downloadName 文件下载时名字
*/
public static void download(HttpServletResponse resp, String name, String downloadName) {
String fileName = null;
try {
fileName = new String(downloadName.getBytes("GBK"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
///home/tomcat/apache-tomcat-9.0.1/files
String realPath = "D:" + File.separator + "apache-tomcat-8.5.15" + File.separator + "files";
// String realPath=File.separator+"home"+File.separator+"tomcat"+File.separator+"apache-tomcat-9.0.1"+File.separator+"files";
String path = realPath + File.separator + name;
File file = new File(path);
resp.reset();
resp.setContentType("application/octet-stream");
resp.setCharacterEncoding("utf-8");
resp.setContentLength((int) file.length());
resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = resp.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
fileName是文件下载之后的名字,filePath是文件所在文件夹地址,path是文件地址,注意设置的响应类型和编码方式
其中File.separator为路径分隔符,他能自动识别是哪个操作系统而使用不同的路径分隔符(windows是‘\’,linux是‘/’)。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/156824.html原文链接:https://javaforall.cn