// 文件上传 mongoDB
@PostMapping("/uploadBytes")
public R uploadBytes(@RequestParam("imgFile") MultipartFile file) {
   //获取上传文件名,包含后缀
   String originalFilename = file.getOriginalFilename();
   //获取后缀
   String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
   //保存的文件名
   String dFileName = UUID.randomUUID() + substring;
   //生成保存文件
   File uploadFile = new File(dFileName);
   System.out.println(uploadFile);
   //将上传文件保存到路径
   try {
       byte[] bytes = file.getBytes();
       String uuid = UUID.randomUUID().toString();
       BaseDocument baseDocument = new BaseDocument();
       baseDocument.setCreateTime(new Date());
       baseDocument.setModifyTime(new Date());
       baseDocument.setId(uuid);
       baseDocument.setBytes(bytes);
       mongodbClient.save(baseDocument);
       return R.ok(uuid);
   } catch (Exception e) {
       e.printStackTrace();
       return R.error(e.getMessage());
   }

}

// 文件上传回显
@PostMapping("/showPic")
public void showPic(@RequestBody String uuid, HttpServletResponse response) {
   service.showPicture(uuid, response);
   //return R.ok().put("data", data);
}
Mongodb工具类
@Component
public class MongodbServiceImpl implements IMongodbService {
   @Resource
   private MongodbClient<BaseDocument> mongodbClient;
   @Override
   public int save(BaseDocument document){
      return mongodbClient.insert(document);
   }
   @Override
   public int delete(String id){
       return mongodbClient.delete(id,BaseDocument.class);
   }
   @Override
   public BaseDocument findOne(String id){
       return mongodbClient.find(id,BaseDocument.class);
   }
   @Override
   public int update(MongodbQuery query, BaseDocument document){
       return mongodbClient.update(query,document,BaseDocument.class,true,false);
   }
   // 图片回显
   public String showPic(String uuid)  {
       BaseDocument baseDocument = findOne(uuid);
       byte[] bytes = baseDocument.getBytes();
       BASE64Encoder encoder = new BASE64Encoder();
       String data = encoder.encode(bytes);
       return data;
   }
}
Last modification:February 20th, 2020 at 10:50 am