Sping Boot MongDb实现文件 图片 上传和下载

Sping Boot MongoDb实现文件上传和下载

文件的上传

    /**
     * 单文件上传
     *
     * 返回: 文件类型,文件名称,mogo路径,磁盘路径(暂定)
     */
    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public ExtResult<FileVo> upload(@Param("file") MultipartFile file, HttpServletRequest request) {
        String code=request.getParameter("code");
        if(code==null){
            code="default";
        }
        FileVo vo = uploadService.upload(file,code);
        return ExtResult.ok(vo);
    }
    /**
     * 单文件上传
     */
    @Override
    public FileVo upload(MultipartFile file, String code) {
        //文件后缀名,文件大小校验
        checkFile(file);

        FileVo vo = new FileVo();
        String fileName = file.getOriginalFilename();
        //文件类型和后缀名
        String contentType = file.getContentType();
        String type = fileName.substring(fileName.lastIndexOf("."));
        try {
//            //是否要新建目录
            String filenameId = FileUtil.MultipartFileMD5(file);
            String mdFilename = filenameId+ fileName.substring(fileName.lastIndexOf("."));
            InputStream is = file.getInputStream();
            //保存到mongo
            Query query = Query.query(Criteria.where("filename").is(mdFilename));
            GridFSFile gridFile = gridFsTemplate.findOne(query);
            ObjectId objectId ;
            if(gridFile!=null) {
                objectId = gridFile.getObjectId();
            }else{
                objectId = gridFsTemplate.store(is, mdFilename, contentType);
            }
            vo.setFilename(fileName);
            vo.setFileType(type);
            vo.setMongodbId(String.valueOf(objectId));
        } catch (Exception e) {
            log.error("业务异常={}", e.getMessage(), e);
            throw new BusinessException(ErrorCodeEnum.SDK_FILE_UPLOAD_FAILURE);
        }
        return  vo;
    }
@Data
@ApiModel(value = "文件上传响应类")
public class FileVo implements Serializable {

    @ApiModelProperty(value = "Mongodb标识Id")
    private String mongodbId;
    @ApiModelProperty(value = "磁盘地址")
    private String fileUrl;
    @ApiModelProperty(value = "原文件名")
    private String filename;
    @ApiModelProperty(value = "文件后缀类型")
    private String fileType;

}

文件的预览

    /**
     * 预览图片
     */
    @GetMapping(value = "/show")
    @ApiOperation(value = "预览图片")
    public ExtResult show(String mongoId, HttpServletResponse response)throws IOException {
        uploadService.show(mongoId,response);
        return ExtResult.ok();
    }
    /**
     * 预览文件:无水印
     */
     
    @Autowired
    private GridFsTemplate gridFsTemplate;
    @Autowired
    private MongoDbFactory mongoDbFactory;
    //新版本写法 private MongoDatabaseFactory mongoDbFactory;
  
  
    /**
     * 预览文件 有水印
     */
    @Override
    public void show(String mongoId, HttpServletResponse response) throws IOException {
        GridFSFile gridFSFile = this.getById(mongoId);
        if (gridFSFile != null) {
            GridFSBucket bucket = GridFSBuckets.create(mongoDbFactory.getDb());
            GridFSDownloadStream gridFSDownloadStream = bucket.openDownloadStream(gridFSFile.getObjectId());
            GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
            //水印 hutool工具类
            ClassPathResource classPathResource = new ClassPathResource(WATERMARK);
            ImageUtil.addWatermark(
                        gridFsResource.getInputStream(),
                        classPathResource.getFile(),
                        response.getOutputStream(),
                    0.5f
                    );
        }else {
            throw new BusinessException(ErrorCodeEnum.SDK_FILE_NOT_EXIT);
        }
    }
    /**
     * 据id返回文件
     */
    public GridFSFile getById(String mongoId){
        Query query = Query.query(Criteria.where("_id").is(mongoId));
        GridFSFile gfsFile = gridFsTemplate.findOne(query);
        return gfsFile;
    }
    /**
     * 预览文件:无水印
     */
    @Override
    public void showNoWater(String mongoId, HttpServletResponse response) throws IOException {
        GridFSFile gridFSFile = this.getById(mongoId);
        if (gridFSFile != null) {
            GridFSBucket bucket = GridFSBuckets.create(mongoDbFactory.getDb());
            GridFSDownloadStream gridFSDownloadStream = bucket.openDownloadStream(gridFSFile.getObjectId());
            GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
            IOUtils.copy(gridFsResource.getInputStream(), response.getOutputStream());
        }else {
            throw new BusinessException(ErrorCodeEnum.SDK_FILE_NOT_EXIT);
        }
    }
    /**
     * 文件类型、大小是否正确
     */
    public void checkFile(MultipartFile multipartFile){
        if (multipartFile==null) {
            throw new BusinessException(ErrorCodeEnum.SDK_FILE_NOT_EXIT);
        }
        String name = multipartFile.getOriginalFilename();
        String documentType = name.substring(name.lastIndexOf("."));
        //文件类型是否正确
        String fileLastType = documentType.toLowerCase();
        List<String> lastType = SdkConstant.UploadFile.FILE_MAP;
        if(!lastType.contains(fileLastType)) {
            throw new BusinessException(ErrorCodeEnum.SDK_FILE_TYPE_INCORRECT);
        }
        if (multipartFile.getSize() > SdkConstant.UploadFile.MAX_UPLOAD_SIZE) {
            throw new BusinessException(ErrorCodeEnum.SDK_FILE_BIG);
        }
    }

文件的下载

    @GetMapping(value = "/download")
    @ApiOperation(value = "文件下载")
    public void downloadFile(String mongoId,
                             HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(StrUtil.isNotBlank(mongoId)) {
            uploadService.downFile(mongoId, request, response);
        }
    }
    /**
     * 文件下载
     */
    @Override
    public void downFile(String mongoId, HttpServletRequest request, HttpServletResponse response)throws IOException{
        GridFSFile gfsFile = this.getById(mongoId);
        if(gfsFile==null){
            throw  new BusinessException(ErrorCodeEnum.SDK_FILE_NOT_EXIST);
        }
        InputStream is = GridFSBuckets.create(mongoDbFactory.getDb()).openDownloadStream(gfsFile.getObjectId());
        GridFsResource gridFsResource=new GridFsResource(gfsFile,is);
        String fileName = gfsFile.getFilename().replace(",", "");
        this.fileDown(gridFsResource.getInputStream(),fileName,request,response);
    }
    private void fileDown(InputStream inputStream,
                          String fileName,
                          HttpServletRequest request,
                          HttpServletResponse response)throws IOException{
        //处理中文文件名乱码
        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("UTF-8"), "ISO-8859-1");
        }
        // 通知浏览器进行文件下载
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        IOUtils.copy(inputStream,response.getOutputStream());
    }
 //下载文件添加水印
    private void fileWaterDown(InputStream inputStream,
                          String fileName,
                          HttpServletRequest request,
                          HttpServletResponse response)throws IOException{
        //处理中文文件名乱码
        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("UTF-8"), "ISO-8859-1");
        }
        // 通知浏览器进行文件下载
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        ClassPathResource classPathResource = new ClassPathResource(WATERMARK);
        ImageUtil.addWatermark(
                inputStream,
                classPathResource.getFile(),
                response.getOutputStream(),
                0.5f
        );
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值