MongoDB-4 GridFS 文件存儲


1. 配置config


<code>spring:
data:
mongodb:
uri: mongodb://username:[email protected]:27017
database: mydb/<code>


<code>@Component
public class WebConfig {
@Value("${spring.data.mongodb.database}")
private String mongodb;

@Bean
public GridFSBucket getGridFSBucket(MongoClient mongoClient){
MongoDatabase database = mongoClient.getDatabase(mongodb);
GridFSBucket bucket = GridFSBuckets.create(database);
return bucket;
}

}/<code>


2. 基於gridfs的上傳,讀取與下載

<code>@Autowired
private GridFSBucket gridFSBucket;


/**
* 創建文件到GirdFS
* @param model
* @return
* @throws Exception
*/
@GetMapping("/addToGridFS")
@ResponseBody
public Object addToGirdFS(Model model) throws Exception {

// 聲明freemarker的配置類
Configuration cfg = new Configuration(Configuration.getVersion());

// 聲明freemarker模板所需要加載的目錄位置
String classpath = this.getClass().getResource("/").getPath();
cfg.setDirectoryForTemplateLoading(new File(classpath + "templates"));
// System.out.println(classpath + "templates");

// 構建數據
model = makeModel(model);

// 加載ftl模板
Template template = cfg.getTemplate("user.ftl", "utf-8");
// 獲得靜態化後的內容
String htmlContent = FreeMarkerTemplateUtils.processTemplateIntoString(template, model.asMap());

InputStream inputStream = IOUtils.toInputStream(htmlContent);

// 上傳
ObjectId fileId = gridFSBucket.uploadFromStream("1001.html", inputStream);
System.out.println("上傳完成。 文件ID:" + fileId);

// 文件在mongodb中的id
return fileId.toString();
}


/**
* 讀取文件
* @param model
* @return
* @throws Exception
*/
@GetMapping("/readGridFS")
@ResponseBody
public String readGridFS(Model model) throws Exception {

// 獲取文件ID
String objectId = "5e42924980fb940ab75f141a"; // 根據upload後文件ID修改
// 獲取內容
GridFSFindIterable gridFSFindIterable = gridFSBucket.find(Filters.eq("_id", new ObjectId(objectId)));
GridFSFile gridFSFile = gridFSFindIterable.first();
System.out.println("filename: " + gridFSFile.getFilename());

return gridFSFile.getFilename();
}

/**
* 從gridfs中下載文件
* @throws Exception
*/
@GetMapping("/downloadGridFS")
@ResponseBody
public String downloadGridFS() throws Exception {
// 獲取文件ID
String objectId = "5e42924980fb940ab75f141a";
// 獲取文件流,定義存放位置和名稱
File file = new File(htmlTarget + "/1001.html");
// 創建輸出流
OutputStream os = new FileOutputStream(file);
// 執行下載
gridFSBucket.downloadToStream(new ObjectId(objectId), os);
System.out.println("下載成功");
return "ok";
}
@GetMapping("/downloadGridFSByFileName")
@ResponseBody
public String downloadGridFSByFileName() throws Exception {
// 獲取文件ID
String filename = "1001.html";
// 獲取文件流,定義存放位置和名稱
File file = new File(htmlTarget + "/" + filename);
// 創建輸出流
OutputStream os = new FileOutputStream(file);
// 執行下載
gridFSBucket.downloadToStream(filename, os);
System.out.println("下載成功");
return "ok";
}

/**
* 刪除文件
* @param model
* @return
* @throws Exception
*/
@GetMapping("/deleteGirdFS")
@ResponseBody
public String deleteGirdFS(Model model) throws Exception {
// 獲取文件ID

String objectId = "5e42924980fb940ab75f141a";
// 執行刪除
gridFSBucket.delete(new ObjectId(objectId));
return "ok";
}/<code>


5. 整合SpringBoot作為文件服務展示

當然也能和nginx放在一起使用

<code>    /**
* 藉助nginx+springboot來訪問gridfs中的文件內容
* @param fileName
* @return
* @throws Exception
*/
@GetMapping("/detail/{fileName}")
public void detail(@PathVariable("fileName") String fileName, HttpServletResponse response) throws Exception {

response.setContentType("text/html;charset=utf-8");
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
gridFSBucket.downloadToStream(fileName, outputStream);

// 方式2
// GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(fileName);
// GridFsResource gridFsResource = new GridFsResource(gridFSDownloadStream.getGridFSFile(), gridFSDownloadStream);

// String data = IOUtils.toString(gridFsResource.getInputStream(), "UTF-8");
// System.out.println(data);

// out.write(data.getBytes("UTF-8"));
// out.write("風間影月".getBytes("UTF-8"));
} finally {
outputStream.close();
}
}/<code>


分享到:


相關文章: