MongoDB保存附件文件

Service层:

/**
 * @className: MongoServiceImpl
 * @author: lianglong
 * @create: 2023-03-29 09:57
 */
@Service
public class MongoServiceImpl implements IMongoService {

 
    @Autowired
    private SecondMongoRepository secondMongoRepository;
    @Autowired
    private GridFsTemplate gridfsTemplate;
    @Resource
    private MongoDatabaseFactory secondMongoFactory;

   
    /**
     * 根据id查询文件
     */
    public GridFSFile findFileById(Object id) throws Exception{
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        return gridfsTemplate.findOne(query);
    }

    /**
     * 保存文件
     * @param file
     */
    public String saveFile(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String type=filename.substring(filename.lastIndexOf(".")-1,filename.length());
        ObjectId id = gridfsTemplate.store(file.getInputStream(), UUID.randomUUID().toString().replaceAll("-","")+type, file.getContentType());
        return id.toString();
    }

    /**
     * 根据id删除文件
     */
    public void deleteFileById(Object id){
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        gridfsTemplate.delete(query);
    }

    public byte[] downloadFile(String objectId, OutputStream out) throws Exception {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(objectId));
        GridFSFile gridFSFile = gridfsTemplate.findOne(query);
        GridFSBucket bucket = GridFSBuckets.create(secondMongoFactory.getMongoDatabase());
        GridFSDownloadStream in = bucket.openDownloadStream(gridFSFile.getObjectId());
        GridFsResource resource = new GridFsResource(gridFSFile,in);
        InputStream inputStream = resource.getInputStream();
        byte[] f = getBytes(inputStream);
        return  f;
    }

    private byte[] getBytes(InputStream inputStream) throws  Exception{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int  i = 0;
        while (-1!=(i=inputStream.read(b))){
            bos.write(b,0,i);
        }
        return bos.toByteArray();
    }

Controller层

/**
     * 保存文件
     */
    @RequestMapping(value = "/saveFile", method = RequestMethod.POST)
    public Result<?> saveFile(@RequestParam("file") MultipartFile file) throws Exception {
        Map<String, Object> param = new HashMap<>();
        if (null != file) {
            //存文件返回id
            String id = mongoService.saveFile(file);
            System.out.println("id:  "+id);
            //文件名
            String fileName = file.getOriginalFilename();
            param.put("file_id", id);
            param.put("file_name", fileName);
        }
        return Result.OK("保存成功!", param);
    }

    /**
     * 获取mongo中的文件流,图片或者视频
     */
    @RequestMapping(value = "/downloadFile")
    public String downloadFile(HttpServletResponse response, HttpServletRequest request) throws Exception {
        String id = request.getParameter("id");
        OutputStream out = null;
        byte[] file = null;
        try {
            out = new BufferedOutputStream(response.getOutputStream());
            file = mongoService.downloadFile(id,out);
            out.write(file);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        String data = file != null ? encoder.encode(file) : "";
        return data;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值