/** * 上传文件至GridFs * @param gridFsTemplate * @param file */ 需要自行导入jar包 public static ObjectId uploadFile(GridFsTemplate gridFsTemplate, MultipartFile file){ try { //获取文件的MD5 String md5 = DigestUtils.md5DigestAsHex(file.getInputStream()); Query query = new Query(); query.addCriteria(Criteria.where("md5").is(md5)); //根据文件MD5值查询 GridFSFile gridFSDBFile = gridFsTemplate.findOne(query); //如果不存在重复文件则存入GridFS if(CommentUtils.isEmpty(gridFSDBFile)) { log.info("upload file.."); DBObject metaData = new BasicDBObject(); metaData.put("createdDate", new Date()); String fileName = file.getOriginalFilename(); log.info("File Name: " + fileName); ObjectId objectId = gridFsTemplate.store(file.getInputStream(), fileName, file.getContentType(), metaData); log.info("File upload: " + file.getContentType()); return objectId; } return gridFSDBFile.getObjectId(); } catch (Exception e) { log.error("IOException: " + e); throw new BadRequestException(ExceptionEnum.UPLOAD_FILE_FILE.getMessage()); } }