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;
}