1 /**
2 * 传统下载
3 * @param filename 文件名称
4 */
5 @RequestMapping(value="download", method={RequestMethod.GET, RequestMethod.POST})
6 public void download(HttpServletRequest request, HttpServletResponse response, String filename) {
7 String realpath = request.getServletContext().getRealPath("/");
8 // 输出文件路径
9 String filepath = realpath + filedir + "/" + filename;
10 response.setContentType("application/octet-stream;charset=utf-8");
11 response.setHeader("Content-Disposition", "attachment;filename=" + filename);
12 response.addHeader("Pragma", "no-cache");
13 response.addHeader("Cache-Control", "no-cache");
14 try {
15 OutputStream os = response.getOutputStream();
16 InputStream is = new BufferedInputStream(new FileInputStream(filepath));
17 byte[] buffer = new byte[4096];
18 int length = 0;
19 while((length = is.read(buffer)) > 0) {
20 os.write(buffer, 0, length);
21 }
22 is.close();
23 os.close();
24 } catch (Exception e) {
25 e.printStackTrace();
26 }
27 }
28
29 /**
30 * SpringMVC下载
31 * @return 文件名称
32 */
33 @RequestMapping(value="graceDownload", method={RequestMethod.GET, RequestMethod.POST})
34 public ResponseEntity<byte[]> graceDownload(HttpServletRequest request, String filename) {
35 String realpath = request.getServletContext().getRealPath("/");
36 // 输出文件路径
37 String filepath = realpath + filedir + "/" + filename;
38 byte[] byteArray = null;
39 try {
40 byteArray = FileUtils.readFileToByteArray(new File(filepath));
41 } catch(Exception e) {
42 e.printStackTrace();
43 }
44 HttpHeaders headers = new HttpHeaders();
45 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
46 headers.setContentDispositionFormData("attachment", filename);
47 ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(byteArray, headers, HttpStatus.CREATED);
48 return responseEntity;
49 }
本文来源于互联网:Java传统下载和SpringMVC下载