SpringBoot文件上传下载

逃离我推掉我的手 2022-02-13 02:21 527阅读 0赞

前言

博主github

博主个人博客http://blog.healerjean.com

习惯了使用OSS傻瓜式上传,是不是都快忘记写原生的上传了,今天小米的项目中需要用一下,所以之类简单总结下 吧






















MultipartFile file 方法名字 内容
file.getContentType() image/png
file.getOriginalFilename() AAAA.png
file.getName() file

1、上传

1、FileUtils.copyInputStreamToFile

  1. File localFile = new File(tempFile,fileName);
  2. FileUtils.copyInputStreamToFile(file.getInputStream(),localFile);

2、file.transferTo

  1. 我使用这种方式报错了,没有深入研究,网上说是jar包问题
  2. <dependency>
  3. <groupId>commons-fileupload</groupId>
  4. <artifactId>commons-fileupload</artifactId>
  5. <version>1.3.1</version>
  6. </dependency>
  7. File localFile = new File(tempFile,fileName);
  8. file.transferTo(localFile);

3、正常读取

  1. byte[] bytes = file.getBytes();
  2. File localFile = new File(tempFile,fileName);
  3. BufferedOutputStream stream = new BufferedOutputStream(
  4. new FileOutputStream(localFile));
  5. stream.write(bytes);
  6. BufferedOutputStream out = new BufferedOutputStream(
  7. new FileOutputStream(localFile));
  8. in = file.getInputStream();
  9. int num = 0;
  10. byte[] b = new byte[1024];
  11. while((num = in.read(b)) != -1) {
  12. out.write(b, 0, num);
  13. }
  14. @Override
  15. public String upload(MultipartFile file){
  16. String name = UUID.randomUUID().toString().replaceAll("-", "");
  17. LocalDateTime dateTime = LocalDateTime.now();
  18. DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  19. String localTime = df.format(dateTime);
  20. //文件存储最终目录
  21. File tempFile = new File("/User/healerjean/Desktop"+localTime);
  22. if(!tempFile.exists()){
  23. tempFile.mkdirs();
  24. }
  25. String fileName = file.getOriginalFilename();
  26. fileName = name+fileName.substring(fileName.lastIndexOf(".") );
  27. File localFile = new File(tempFile,fileName);
  28. try {
  29. FileUtils.copyInputStreamToFile(file.getInputStream(),localFile);
  30. //2、 file.transferTo(localFile);
  31. } catch (IOException e) {
  32. throw new RuntimeException(e.getMessage(),e);
  33. }
  34. return fileName;
  35. }

2、下载

  1. @GetMapping("/{id}")
  2. public void downLoad(HttpServletResponse response,String folder) {
  3. try {
  4. InputStream inputStream = new FileInputStream(new File(folder));
  5. OutputStream outputStream = response.getOutputStream();
  6. response.setContentType("application/x-download");
  7. response.setHeader("Content-Disposition", "attachment;filename=test.txt");
  8. IOUtils.copy(inputStream, outputStream);
  9. outputStream.flush();
  10. } catch (Exception e) {
  11. }
  12. }

ContactAuthor

发表评论

表情:
评论列表 (有 0 条评论,527人围观)

还没有评论,来说两句吧...

相关阅读