|
@@ -0,0 +1,92 @@
|
|
|
+package com.zswl.dataservicestarter.service;
|
|
|
+
|
|
|
+import com.mongodb.client.gridfs.model.GridFSFile;
|
|
|
+import org.bson.types.ObjectId;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.data.mongodb.core.query.Criteria;
|
|
|
+import org.springframework.data.mongodb.core.query.Query;
|
|
|
+import org.springframework.data.mongodb.gridfs.GridFsResource;
|
|
|
+import org.springframework.data.mongodb.gridfs.GridFsTemplate;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+
|
|
|
+import java.io.IOException;
|
|
|
+import java.io.InputStream;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @author TRX
|
|
|
+ * @date 2024/3/25
|
|
|
+ */
|
|
|
+@Service
|
|
|
+public class GridFsService {
|
|
|
+ @Autowired GridFsTemplate gridFsTemplate;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 存储文件数据
|
|
|
+ *
|
|
|
+ * @param content
|
|
|
+ * @param filename
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ public String addGridFs(InputStream content, String filename) {
|
|
|
+ ObjectId objectId = gridFsTemplate.store(content, filename);
|
|
|
+ return objectId.toHexString();
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 根据ID查询文件
|
|
|
+ *
|
|
|
+ * @param id
|
|
|
+ * @return
|
|
|
+ * @throws IOException
|
|
|
+ */
|
|
|
+ public InputStream getFile(String id) throws IOException {
|
|
|
+ GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));
|
|
|
+ if (file != null) {
|
|
|
+ GridFsResource resource = gridFsTemplate.getResource(file);
|
|
|
+ return resource.getInputStream();
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 根据名称查询多个文件
|
|
|
+ *
|
|
|
+ * @param name
|
|
|
+ * @return
|
|
|
+ * @throws IOException
|
|
|
+ */
|
|
|
+ public List<InputStream> getFilesByName(String name) throws IOException {
|
|
|
+ List<InputStream> inputStreams = new ArrayList<>();
|
|
|
+ Query query = new Query(Criteria.where("filename").is(name));
|
|
|
+ List<GridFSFile> files = gridFsTemplate.find(query).into(new ArrayList<>());
|
|
|
+
|
|
|
+ for (GridFSFile file : files) {
|
|
|
+ GridFsResource resource = gridFsTemplate.getResource(file);
|
|
|
+ InputStream inputStream = resource.getInputStream();
|
|
|
+ if (inputStream != null) {
|
|
|
+ inputStreams.add(inputStream);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return inputStreams;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 根据文件删除文件
|
|
|
+ *
|
|
|
+ * @param filename
|
|
|
+ */
|
|
|
+ public void deleteFileByName(String filename) {
|
|
|
+ gridFsTemplate.delete(new Query(Criteria.where("filename").is(filename)));
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 根据文件ID删除文件
|
|
|
+ *
|
|
|
+ * @param id
|
|
|
+ */
|
|
|
+ public void deleteFileById(String id) {
|
|
|
+ gridFsTemplate.delete(new Query(Criteria.where("_id").is(id)));
|
|
|
+ }
|
|
|
+}
|