GridFs文件上传下载

2023-03-01 18:09:51 浏览数 (1)

文章目录[隐藏]

  • 业务层
  • 上传
  • 下载
  • 预览
  • 配置文件

业务层

代码语言:javascript复制
public class FileMonService {

    /**
     * 操作GridFs接口
     */
    private final GridFsTemplate gridFsTemplate;

    @Autowired
    public FileMonService(GridFsTemplate gridFsTemplate) {
        this.gridFsTemplate = gridFsTemplate;
    }


    public ObjectId gridFsFile(MultipartFile file)throws FileUploadException {
        try {
            ObjectId objectId = gridFsTemplate.store(file.getInputStream(),file.getOriginalFilename(), file.getContentType());
            log.info("object-id:[{}]",objectId);
            return objectId;
        } catch (IOException e) {
            throw new FileUploadException("文件上传错误!");
        }
    }

    public GridFSFile gridFsDownload(String fileId) {
        return StringUtils.isNotBlank(fileId)?gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId))):null;
    }


    public void deleteFile(String fileId) {
        gridFsTemplate.delete(Query.query(Criteria.where("_id").is(fileId)));
    }

}

上传

代码语言:javascript复制
    @ApiOperation(value = "单文件上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public DataJsonResult gridFsFile(@RequestPart("file") MultipartFile file){
        try {
            return new DataJsonResult<>(true,fileMonService.gridFsFile(file).toString());
        }catch (FileUploadException e){
            return new DataJsonResult<>(new JsonResult(false,e.getMessage()));
        }
    }

下载

代码语言:javascript复制
    @ApiOperation(value = "单文件下载")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public DataJsonResult gridFsDownload(@RequestParam("fileId") String fileId, HttpServletRequest request, HttpServletResponse response) {
        //查询单个文件
        GridFSFile gfsFile = fileMonService.gridFsDownload(fileId);

        if (gfsFile == null) {
            return new DataJsonResult<>( false, "文件可能不存在,请重试");
        }
        GridFsResource gridFsResource = new GridFsResource(gfsFile, GridFSBuckets.create(mongoDbFactory.getDb()).openDownloadStream(gfsFile.getObjectId()));
        String fileName = gfsFile.getFilename().replace(",", "");
        //处理文件名乱码
        try {
            if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
                    request.getHeader("User-Agent").toUpperCase().contains("TRIDENT") ||
                    request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {

                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                //非IE浏览器的处理:
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            //通知浏览器进行文件下载
            response.setHeader("Content-Disposition", "attachment;filename=""   fileName   """);
            IOUtils.copy(gridFsResource.getInputStream(), response.getOutputStream());
            return new DataJsonResult<>(true,"文件下载成功");
        } catch (IOException e) {
            return new DataJsonResult<>(new JsonResult(false,"文件下载失败"));
        }
    }

预览

代码语言:javascript复制
@ApiOperation(value = "单文件预览-文件id")
    @RequestMapping(value = "/preview", method = RequestMethod.GET)
    public R gridFsPreview(@RequestParam("fileId") String fileId, HttpServletRequest request, HttpServletResponse response) {
        //查询单个文件
        GridFSFile gfsFile = fileMonService.gridFsDownload(fileId);
        if (gfsFile == null) {
            return failed("文件可能不存在,请重试");
        }
        GridFsResource gridFsResource = new GridFsResource(gfsFile, GridFSBuckets.create(mongoDbFactory.getDb()).openDownloadStream(gfsFile.getObjectId()));
        String fileName = gfsFile.getFilename().replace(",", "");
        //处理文件名乱码
        try {
            if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
                    request.getHeader("User-Agent").toUpperCase().contains("TRIDENT") ||
                    request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {

                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                //非IE浏览器的处理:
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            //通知浏览器进行文件预览
            response.setContentType("image/svg xml;charset=UTF-8");
            response.addHeader("Accept-Ranges","bytes");
            IOUtils.copy(gridFsResource.getInputStream(), response.getOutputStream());
            return null;
        } catch (IOException e) {
            return failed("文件下载失败");
        }
    }

配置文件

代码语言:javascript复制
spring.data.mongodb.uri=mongodb://testuser:123456@10.10.10.10:27017/gridfs
spring.data.mongodb.database=gridfs
spring.data.mongodb.authentication-database=admin
#允许上传最大的文件大小
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB

0 人点赞