java本地檔案下載功能
阿新 • • 發佈:2019-02-08
檔案下載部分:以二進位制流資料下載,也是最常見的一種
@RequestMapping(value="/downloadqrcodes",method={RequestMethod.GET,RequestMethod.POST})
public ResponseEntity<byte[]> download(String filename,HttpServletRequest req,HttpServletResponse res) throws Exception {System.out.println(req.getCharacterEncoding());
System.out.println(filename);
ApplicationContext ctx = GetApplication.getApp();
QrcodepersonMapper qrcodepersonMapper = (QrcodepersonMapper) ctx.getBean("qrcodepersonMapper");
Qrcodeperson qrcodeperson = qrcodepersonMapper.selectByPrimaryKey(Integer.parseInt(filename));
String filen = qrcodeperson.getUrlname();
//下載檔案路徑
//filename="何家勁.jpg";
String path = req.getServletContext().getRealPath("/file/");
File file = new File(path+File.separator+filen);
System.out.println("檔案路徑為:"+path+File.separator+filen);
HttpHeaders headers = new HttpHeaders();
//下載顯示的檔名,解決中文名稱亂碼的問題
String downloadFileName = new String(filen.getBytes("UTF-8"), "ISO-8859-1"); //為了下載下來的名字和檔案的名字相同
System.out.println(downloadFileName);
//通知瀏覽器以attachment(下載方式)開啟圖片
headers.set(filen, null);
headers.setContentDispositionFormData("attachment", downloadFileName);
//application/octet-stream:二進位制流資料(最常見的檔案下載)
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//201 HttpStatus.CREATED
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers,HttpStatus.CREATED);
}