@RequestMapping("/download")
@ResponseBody
public String downloadFile(String realPath ,String fileName, HttpServletRequest request, HttpServletResponse response) {
// 设置文件名,根据业务需要替换成要下载的文件名
String fileName = fileNamePath.substring(fileNamePath.lastIndexOf("/") + 1, fileNamePath.length());
if (fileName != null) {
//设置文件路径
realPath = "D:/ssmDoc/uploaded_files/";
File file = new File(realPath , fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
return "success";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return "文件不存在";
}
文件下载
最新推荐文章于 2024-01-12 23:08:35 发布