1. 程式人生 > >Spring-mvc後臺下載功能一種實現ResponseEntity

Spring-mvc後臺下載功能一種實現ResponseEntity

public ResponseEntity downloadFile() throws IOException {
   File file = fileService.getDownloadFile();//給回要下載的檔案
   String destFileName = new String(
         file.getName().getBytes("gb2312"), "iso8859-1");//防止亂碼
   //響應頭,告訴瀏覽器
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
   headers.setContentDispositionFormData("attachment", destFileName);

   return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
}