packagecom.maybesuch.controller;importcom.mongodb.client.gridfs.model.GridFSFile;importorg.apache.commons.io.IOUtils;importorg.bson.types.ObjectId;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.data.mongodb.core.query.Criteria;importorg.springframework.data.mongodb.core.query.Query;importorg.springframework.data.mongodb.gridfs.GridFsResource;importorg.springframework.data.mongodb.gridfs.GridFsTemplate;import org.springframework.web.bind.annotation.*;importorg.springframework.web.multipart.MultipartFile;importjava.io.IOException;importjava.io.InputStream;importjava.util.HashMap;importjava.util.Map;/***@author: maybesuch
*@version: 1.0
* @Description : GridFS文件基本操作
* @Date : 2020/1/8 10:16
* @Copyright : Copyright (c) 2020 All Rights Reserved
**/@RestController
@RequestMapping("/gridfs")public classGridFSController {
@AutowiredprivateGridFsTemplate gridFsTemplate;/*** 上传文件
*
*@parammultipartFile 文件
*@return上传成功文件id*/@PostMapping("/upload")public String uploadFile(@RequestParam(value = "file") MultipartFile multipartFile) {//设置meta数据值
Map metaData = new HashMap<>();
metaData.put("tags", "test");//...
try(
InputStream inputStream=multipartFile.getInputStream();
) {//获取文件的源名称
String fileName =multipartFile.getOriginalFilename();//进行文件存储
ObjectId objectId =gridFsTemplate.store(inputStream, fileName, metaData);//返回文件的id
returnobjectId.toHexString();
}catch(IOException e) {
e.printStackTrace();
}return null;
}/*** 获取文件信息
*@paramfileId 文件id*/@GetMapping("/get/{fileId}")public void getFile(@PathVariable("fileId") String fileId) {//根据id查询文件
GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));if (gridFSFile == null) {throw new RuntimeException("No file with id: " +fileId);
}//获取流对象
GridFsResource resource =gridFsTemplate.getResource(gridFSFile);/*可根据实际需求进行数据的获取*/
try{//获取流中的数据
String content = IOUtils.toString(resource.getInputStream(), "UTF-8");//获取byte[]信息
byte[] bytes =IOUtils.toByteArray(resource.getInputStream());
}catch(IOException e) {
e.printStackTrace();
}
}/*** 删除文件
*@paramfileId 文件id*/@DeleteMapping("/delete")public void deleteFile(@RequestParam(value = "fileId") String fileId) {//根据文件id删除fs.files和fs.chunks中的记录
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(fileId)));
}
}