其实spring已经对其进行了封装,示例如下:
/**
* 文档下载
* @param fileName
* @param file
* @return
* @throws IOException
*/
public ResponseEntity<byte[]> download(String fileName, File file) throws IOException{
String dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", dfileName);
return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
进行调用:
@RequestMapping("/download")
public ResponseEntity<byte[]> downloadFile(@RequestParam("fileName") String fileName) throws IOException {
if (fileName != null) {
//String realPath = request.getServletContext().getRealPath("resources/files/");
String realPath = "E:\\work";
File file = new File(realPath, fileName);
if (file.exists()) {
return download(fileName, file);
}
System.out.println("====文件路径不存在");
}
return null;
}
如果不是基于springMvc或者spring boot,那么下载就必须这样写:
/**
* 文件下载
* @Description:
* @param fileName
* @param request
* @param response
* @return
*/
@RequestMapping("/download")
public String downloadFile(@RequestParam("fileName") String fileName,
HttpServletRequest request, HttpServletResponse response) {
if (fileName != null) {
String realPath = request.getServletContext().getRealPath(
"WEB-INF/File/");
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);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
return null;
}
转自:http://www.imooc.com/article/2760