在工作中经常会遇到为文件下载的功能,但因为公司的各种下载时的要求不同,所以都在下载功能上或多或少的加减一些。 今天就总结一下我写过的上传功能MVC的思想 controller层:
@GetMapping("/download/downloadZip")
@ResponseBody
public void downloadZip(@Param("downloadPath") String downloadPath, HttpServletRequest request, HttpServletResponse response) {
String down = fileUploadService.downloadPathFile(downloadPath, request, response);
}
Service层–接口:
/**
* @Description:下载
* @Param downloadPath 文件路径
*/
String downloadPathFile(String downloadPath, HttpServletRequest request, HttpServletResponse response);
Service层–实现类
@Override
public String downloadPathFile(String path, HttpServletRequest request, HttpServletResponse response) {
File file = new File(path);
String fileName = file.getName();
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);
}
file.delete();
return "下载成功";
} 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 "下载失败";
}
|