基于SpringWeb MultipartFile文件上传、下载功能

打印 上一主题 下一主题

主题 565|帖子 565|积分 1695

在Web开辟中,文件上传是一个常见的功能需求。Spring框架提供了MultipartFile接口,用于处理文件上传请求。MultipartFile可以代表一个多部分文件上传请求中的一个文件,提供了一系列方法用于获取文件的各种属性和内容,使得在后端处理文件上传变得非常方便。下面我们将介绍MultipartFile在Web应用中的几种常见利用场景。
1. 图片上传
在Web应用中,图片上传是一种常见的场景。用户必要上传头像、相片、证件照等图片文件,而后端必要吸收并保存这些文件。利用MultipartFile接口可以轻松地实现图片文件的吸收和处理。通过获取文件的原始文件名、内容范例、巨细等属性,我们可以实现对图片文件的有效管理和存储。比方,我们可以将图片文件保存到服务器的文件系统中,或者将其存储到云存储服务中。
2. 文件下载
除了文件上传,文件下载也是Web应用中常见的功能需求。利用MultipartFile接口,我们可以实现文件的下载功能。在服务器端,我们可以将文件作为MultipartFile对象举行处理,并通过设置响应头信息,将文件作为下载内容返回给客户端。客户端吸收到文件后,可以将其保存到本地磁盘或举行其他处理。
3. 文件编辑
在Web应用中,有时候用户必要对上传的文件举行编辑操作,比方修改文件名、修改文件内容等。利用MultipartFile接口,我们可以实现对文件的编辑功能。起首,我们可以通过MultipartFile接口获取上传的文件对象,然后对其举行相应的编辑操作。比方,我们可以修改文件的名称、修改文件的内容等。编辑完成后,我们可以将修改后的文件保存到服务器或返回给客户端。
4. 文件预览和展示
在Web应用中,有时候我们必要将上传的文件举行预览或展示。比方,在文档管理系统中,用户必要预览或下载文档文件。利用MultipartFile接口,我们可以实现文件的预览和展示功能。我们可以将文件作为MultipartFile对象举行处理,然后将其内容转换为适当的格式举行展示。比方,对于PDF文件,我们可以利用PDF阅读器插件举行展示;对于图片文件,我们可以将其直接展示在网页上。
5. 文件批量上传和处理
在实际应用中,有时候用户必要批量上传多个文件,并对这些文件举行处理。利用MultipartFile接口,我们可以实现文件的批量上传和处理功能。我们可以将多个文件作为一个多部分文件上传请求举行处理,然后对每个文件举行相应的操作。比方,我们可以将多个图片文件批量上传到服务器,并对它们举行压缩、裁剪等处理。
代码

  1. package com.javagpt.back.controller;
  2. import com.javagpt.application.context.UserAppContextHolder;
  3. import com.javagpt.application.file.FileApplicationService;
  4. import com.javagpt.application.file.FileDTO;
  5. import com.javagpt.common.annotation.RespSuccess;
  6. import com.javagpt.common.constant.EMConstant;
  7. import io.swagger.annotations.Api;
  8. import io.swagger.annotations.ApiOperation;
  9. import jakarta.servlet.http.HttpServletRequest;
  10. import jakarta.servlet.http.HttpServletResponse;
  11. import lombok.RequiredArgsConstructor;
  12. import lombok.extern.slf4j.Slf4j;
  13. import org.springframework.web.bind.annotation.*;
  14. import org.springframework.web.multipart.MultipartFile;
  15. import java.io.IOException;
  16. @Api(tags = "文件接口")
  17. @Slf4j
  18. @RestController
  19. @RequestMapping(EMConstant.API_V1 + "/file")
  20. @RespSuccess
  21. @RequiredArgsConstructor
  22. public class FileController {
  23.     private final FileApplicationService fileApplicationService;
  24.     @ApiOperation("通用文件上传")
  25.     @PostMapping(value = "/uploadFile")
  26.     public FileDTO uploadFile(@RequestParam("file") MultipartFile multipartFile) throws IOException {
  27.         Long enterpriseId = UserAppContextHolder.getCurrentUser().getEnterpriseId();
  28.         FileDTO fileDTO = fileApplicationService.saveFile(enterpriseId, multipartFile);
  29.         return fileDTO;
  30.     }
  31.     //@PreAuthorize("hasAuthority('mp:file:download')")
  32.     @ApiOperation("下载文件")
  33.     @GetMapping(value = "/downloadFile")
  34.     public void download(@RequestParam(value = "id") Long id, HttpServletResponse response) throws IOException {
  35.         fileApplicationService.downloadFile(response, id, UserAppContextHolder.getCurrentUser().getEnterpriseId());
  36.     }
  37.     @ApiOperation("查看文件信息")
  38.     @GetMapping(value = "/info")
  39.     public FileDTO fileInfo(@RequestParam(value = "id") Long id) throws IOException {
  40.         return fileApplicationService.findById(id);
  41.     }
  42.     @ApiOperation("下载视频")
  43.     @GetMapping(value = "/downloadFile2")
  44.     public void download2(@RequestParam(value = "id") Long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
  45.         fileApplicationService.downloadVideo(request, response, id, UserAppContextHolder.getCurrentUser().getEnterpriseId());
  46.     }
  47. }
复制代码
  1. package com.javagpt.application.file;
  2. import com.javagpt.common.exception.BusinessRuntimeException;
  3. import com.javagpt.common.oos.OssService;
  4. import com.javagpt.common.util.ModelUtils;
  5. import com.javagpt.common.util.SpringResponseUtils;
  6. import com.javagpt.file.entity.FileEntity;
  7. import com.javagpt.file.repository.FileRepository;
  8. import jakarta.servlet.http.HttpServletRequest;
  9. import jakarta.servlet.http.HttpServletResponse;
  10. import lombok.RequiredArgsConstructor;
  11. import lombok.extern.slf4j.Slf4j;
  12. import org.apache.commons.io.FilenameUtils;
  13. import org.apache.commons.io.IOUtils;
  14. import org.apache.commons.lang3.StringUtils;
  15. import org.springframework.http.HttpHeaders;
  16. import org.springframework.stereotype.Service;
  17. import org.springframework.transaction.annotation.Transactional;
  18. import org.springframework.web.multipart.MultipartFile;
  19. import java.io.*;
  20. @Service
  21. @Slf4j
  22. @RequiredArgsConstructor
  23. public class FileApplicationService {
  24.     private final OssService ossService;
  25.     private final FileRepository fileRepository;
  26.     public FileDTO findById(Long id) {
  27.         FileEntity fileEntity = fileRepository.findById(id);
  28.         return ModelUtils.convert(fileEntity, FileDTO.class);
  29.     }
  30.     @Transactional
  31.     public FileDTO saveFile(Long enterpriseId, MultipartFile file) {
  32.         FileEntity fileEntity = saveFile(enterpriseId, file, null);
  33.         return ModelUtils.convert(fileEntity, FileDTO.class);
  34.     }
  35.     @Transactional
  36.     public FileEntity saveFile(Long enterpriseId, MultipartFile file, String fileName) {
  37.         String originalFilename = file.getOriginalFilename();
  38.         String name = StringUtils.isBlank(fileName) ? FilenameUtils.getBaseName(originalFilename) : fileName;
  39.         String suffix = FilenameUtils.getExtension(originalFilename);
  40.         long size = file.getSize();
  41.         FileEntity fileEntity = new FileEntity();
  42.         fileEntity.setName(name).setSuffix(suffix).setSize(size).setEnterpriseId(enterpriseId);
  43.         fileEntity = fileEntity.save();
  44.         String key = fileEntity.getPath();
  45.         InputStream inputStream = null;
  46.         try {
  47.             inputStream = file.getInputStream();
  48.         } catch (IOException e) {
  49.             log.error("saveFile error:", e);
  50.             throw BusinessRuntimeException.error("上传文件失败");
  51.         }
  52.         ossService.uploadFile(inputStream, key);
  53.         IOUtils.closeQuietly(inputStream);
  54.         return fileEntity;
  55.     }
  56.     @Transactional
  57.     public FileEntity saveFile(File file) {
  58.         long size = file.length();
  59.         FileEntity fileEntity = new FileEntity();
  60.         String baseName = FilenameUtils.getBaseName(file.getName());
  61.         String extension = FilenameUtils.getExtension(file.getName());
  62.         fileEntity.setName(baseName).setSuffix(extension).setSize(size);
  63.         fileEntity = fileEntity.save();
  64.         String key = fileEntity.getPath();
  65.         FileInputStream inputStream = null;
  66.         try {
  67.             inputStream = new FileInputStream(file);
  68.             ossService.uploadFile(inputStream, key);
  69.         } catch (FileNotFoundException e) {
  70.             log.error("saveFile error:", e);
  71.             throw BusinessRuntimeException.error("上传文件失败");
  72.         }
  73.         IOUtils.closeQuietly(inputStream);
  74.         return fileEntity;
  75.     }
  76.     public void downloadFile(HttpServletResponse response, Long fileId, Long enterpriseId) throws IOException {
  77.         FileEntity fileEntity = fileRepository.findById(fileId);
  78.         if (fileEntity == null) {
  79.             throw BusinessRuntimeException.error("无效的文件Id");
  80.         }
  81.         String key = fileEntity.getPath();
  82.         InputStream inputStream = ossService.downloadFile(key);
  83.         SpringResponseUtils.writeAndFlushResponse(inputStream, response, fileEntity.fileFullName());
  84.     }
  85.     public void downloadVideo(HttpServletRequest request, HttpServletResponse response, Long fileId, Long enterpriseId) throws IOException {
  86.         FileEntity fileEntity = fileRepository.findById(fileId);
  87.         if (fileEntity == null) {
  88.             throw BusinessRuntimeException.error("无效的文件Id");
  89.         }
  90.         response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
  91.         Long fileSize = fileEntity.getSize();
  92.         long start = 0, end = fileSize - 1;
  93.         //判断前端需不需要分片下载
  94.         if (StringUtils.isNotBlank(request.getHeader("Range"))) {
  95.             response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
  96.             String numRange = request.getHeader("Range").replaceAll("bytes=", "");
  97.             String[] strRange = numRange.split("-");
  98.             if (strRange.length == 2) {
  99.                 start = Long.parseLong(strRange[0].trim());
  100.                 end = Long.parseLong(strRange[1].trim());
  101.                 //若结束字节超出文件大小 取文件大小
  102.                 if (end > fileSize - 1) {
  103.                     end = fileSize - 1;
  104.                 }
  105.             } else {
  106.                 //若只给一个长度  开始位置一直到结束
  107.                 start = Long.parseLong(numRange.replaceAll("-", "").trim());
  108.             }
  109.         }
  110.         long rangeLength = end - start + 1;
  111.         String contentRange = new StringBuffer("bytes ").append(start).append("-").append(end).append("/").append(fileSize).toString();
  112.         response.setHeader(HttpHeaders.CONTENT_RANGE, contentRange);
  113.         response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(rangeLength));
  114.         String key = fileEntity.getPath();
  115.         InputStream inputStream = ossService.downloadFile2(key, start, end);
  116.         SpringResponseUtils.writeAndFlushResponse(inputStream, response, fileEntity.fileFullName());
  117.     }
  118. }
复制代码
总之,MultipartFile接口在Web应用中具有广泛的应用场景,可以实现文件上传、下载、编辑、预览和批量处理等功能。通过熟练把握MultipartFile接口的利用方法和技巧,我们可以更加高效地处理文件上传和下载请求,提升Web应用的用户体验和功能性能。
   本文由博客一文多发平台 OpenWrite 发布!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

郭卫东

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表