- controller

- service

实例代码:
- 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); }
本文介绍了如何在SpringMVC中使用@Controller和@Service,通过@Autowired注入服务,实现文件下载功能。通过调用`downloadArticle`方法,从数据库获取文章内容,将其保存到硬盘并生成HTTP响应头以支持文件下载。
2044

被折叠的 条评论
为什么被折叠?



