SpringBoot 文件的上传、下载

拼搏现实的明天。 2023-02-12 07:27 22阅读 0赞

目录

      • 文件上传
        • yml
        • html 表单
        • controller
        • 说明
      • 文件下载
      • 说明

文件上传

spring-boot-starter-web中已经包含了springmvc的依赖,其中包括上传文件所需的依赖,不需要额外添加依赖。

yml

  1. spring:
  2. servlet:
  3. multipart:
  4. #上传文件的最大体积,默认1MB
  5. max-file-size: 20MB
  6. #请求的最大体积,默认10M
  7. max-request-size: 20MB
  8. #上传文件的保存位置
  9. location: D:/mall/upload

html 表单

  1. <form action="/upload" method="post" enctype="multipart/form-data">
  2. 选择文件:<input name="uploadFile" type="file" multiple /><br />
  3. <button type="submit">上传</button>
  4. </form>

multiple用于多选,不指定multiple默认只能选择一个文件

controller

  1. import org.springframework.beans.factory.annotation.Value;
  2. import org.springframework.web.bind.annotation.PostMapping;
  3. import org.springframework.web.bind.annotation.RequestParam;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import org.springframework.web.multipart.MultipartFile;
  6. import java.io.File;
  7. import java.io.IOException;
  8. import java.util.List;
  9. import java.util.UUID;
  10. @RestController
  11. public class FileUploadController {
  12. @Value("${spring.servlet.multipart.location}")
  13. private static String saveDir;
  14. //如果指定的保存目录不存在,则自动创建
  15. static {
  16. File dir = new File(saveDir);
  17. if (!dir.exists()) {
  18. dir.mkdirs();
  19. }
  20. }
  21. /** * 处理上传文件 * * @param fileList 一个 MultipartFile 封装1个文件,单文件上传用 MultipartFile,多文件用 List<MultipartFile> * @return 处理结果。通常会使用自定义的响应来封装,根据场景确定是否需要返回文件链接 */
  22. @PostMapping("/upload")
  23. public String upload(@RequestParam("uploadFile") List<MultipartFile> fileList) {
  24. //检测用户是否上传了文件,有可能用户只是点击了提交按钮,但并未选择文件
  25. if (!fileList.get(0).isEmpty()) {
  26. // 处理上传文件
  27. for (MultipartFile file : fileList) {
  28. //原文件名。getContentType() 是文件类型,eg. text/plain
  29. String originalFilename = file.getOriginalFilename();
  30. //文件扩展名
  31. String extensionName = originalFilename.substring(originalFilename.lastIndexOf("."));
  32. //使用uuid生成新文件名,防止重名
  33. String newFilename = UUID.randomUUID() + extensionName;
  34. //将临时文件保存至指定目录
  35. try {
  36. file.transferTo(new File(saveDir + "/xxx/" + newFilename));
  37. return "上传成功";
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. return "上传失败";
  41. }
  42. }
  43. }
  44. return "未选择文件,请先选择文件";
  45. }
  46. }

说明

判断用户是否上传了文件,不能用List是否为空来判断,而应该用第一个元素是否为空来判断。

因为List默认自带1个空的MultipartFile时刻准备着,用户不上传文件,List也不为空;用户上传了1个文件,List的元素个数也还是1。

判断MultipartFile是否为空,不能用==null来判断,因为不管有没有上传文件,MultipartFile一定!=null,判断用户是否上传了文件,要用MultipartFile提供的isEmpty()来判断。

文件下载

yml

  1. #自定义配置,下载文件的根目录
  2. download-dir: D:/download

controller

  1. import org.springframework.beans.factory.annotation.Value;
  2. import org.springframework.http.MediaType;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.*;
  5. import javax.servlet.http.HttpServletResponse;
  6. import java.io.*;
  7. @Controller
  8. public class FileDownloadController{
  9. @Value("${download-dir}") //注入application中配置的下载文件根目录
  10. private String filePath;
  11. @RequestMapping("/download/{filename}")
  12. @ResponseBody
  13. public String downLoad(@PathVariable String filename, HttpServletResponse response) throws UnsupportedEncodingException {
  14. File file = new File(filePath + "/" + filename);
  15. System.out.println(filePath+"/"+filename);
  16. //判断文件是否存在,其实不用判断,因为不存在也设置了对应的异常处理
  17. if (file.exists()) { //文件存在
  18. response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  19. response.setCharacterEncoding("UTF-8");
  20. response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename, "UTF-8")); //设置下载文件名,解决文件名中文乱码
  21. byte[] buffer = new byte[1024];
  22. FileInputStream fis = null; //输入流
  23. BufferedInputStream bis = null;
  24. OutputStream os = null; //输出流
  25. try {
  26. os = response.getOutputStream();
  27. fis = new FileInputStream(file);
  28. bis = new BufferedInputStream(fis);
  29. int length;
  30. while ((length=bis.read(buffer)) != -1) {
  31. os.write(buffer,0,length);
  32. }
  33. fis.close();
  34. bis.close();
  35. } catch (FileNotFoundException e) {
  36. e.printStackTrace();
  37. return "文件不存在!";
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. return "下载失败!";
  41. }
  42. return null; //下载成功
  43. }
  44. return "文件不存在";
  45. }
  46. }

链接

  1. <a href="/download/hehua.jpg">下载图片</a>

href中不要带中文

说明

  • 处理上传文件时,通常要往数据库中插入一条记录,记录文件原名、保存路径(uuid文件名,不要带中文)、文件类型、体积、上传时间、上传人
  • 下载文件时,前端给的链接不要带中文,链接可以给保存路径(uuid文件名)、数据库记录的id,后台取出参数,查询数据库得到文件原名及其它信息,设置下载文件名

发表评论

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

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

相关阅读