SpringBoot 文件下载

本文介绍了如何在SpringMVC中使用@Controller和@Service,通过@Autowired注入服务,实现文件下载功能。通过调用`downloadArticle`方法,从数据库获取文章内容,将其保存到硬盘并生成HTTP响应头以支持文件下载。
  • 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);
    }
    
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值