SpringBoot 文件下载

50 阅读1分钟
  • controller
  • service image.png

实例代码:

  • controller @Controller @RequestMapping("download") public class FileDownloadController {

        @Autowired
        FileDownloadService fileDownloadService;
    
        @GetMapping("article/{id}")
        public ResponseEntity<byte[]> downloadArticle(@PathVariable String id) {
            ResponseEntity<byte[]> result = fileDownloadService.downloadArticle(id);
            return result;
        }
    }
    
  • service public ResponseEntity<byte[]> downloadArticle(String articleId) { Article article = articleService.get(articleId); byte[] data = null; // 将 article 保存到硬盘 File file = fileDownloadService.saveArticleInDisk(article.getTitle() , article.getContent()); try { data = FileUtil.toByteArray(file.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } String fileName = file.getName() ; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); try { headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName,"utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return new ResponseEntity<byte[]>( data , headers , HttpStatus.CREATED); }