当前位置: 代码迷 >> 综合 >> Sping Boot MongDb实现文件 图片 上传和下载
  详细解决方案

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

热度:92   发布时间:2023-11-21 16:53:01.0

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);}
    /*** 单文件上传*/@Overridepublic 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();//保存到mongoQuery 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();}
    /*** 预览文件:无水印*/@Autowiredprivate GridFsTemplate gridFsTemplate;@Autowiredprivate MongoDbFactory mongoDbFactory;//新版本写法 private MongoDatabaseFactory mongoDbFactory;/*** 预览文件 有水印*/@Overridepublic 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;}
    /*** 预览文件:无水印*/@Overridepublic 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);}}
    /*** 文件下载*/@Overridepublic 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);}
  相关解决方案