SpringBoot 文件下载

  • controller


  • service


实例代码:

  • controller
    @Controller
    @RequestMapping("download")
    public class FileDownloadController {
    
        @Autowired
        FileDownloadService fileDownloadService;
    
        @GetMapping("article/{id}")
        public ResponseEntity downloadArticle(@PathVariable String id) {
            ResponseEntity result = fileDownloadService.downloadArticle(id);
            return result;
        }
    }
    
  • service
    public ResponseEntity 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( data , headers , HttpStatus.CREATED);
    }
    

你可能感兴趣的:(SpringBoot 文件下载)