使用Springboot整合GridFS實現(xiàn)文件操作
GridFsOperations,實現(xiàn)GridFS文件上傳下載刪除
最近學(xué)習(xí)GridFS,想用它整合springboot弄個文件的上傳下載。
網(wǎng)上查到的很多資料都是使用GridFsTemplate,還有GridFSBucket來實現(xiàn)的,需要各種額外配置Bean。但是看了spring-data-mongodb的官方文檔,以及示例代碼,他們只用到了GridFsOperations,無需其他任何配置。
然后就用GridFsOperations寫了個文件上傳下載的demo,用起來還是很方便的,給大家個參考。
上傳下載刪除功能實現(xiàn)
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
application.properties
#文件上傳下載配置 spring.servlet.multipart.max-file-size=1024MB spring.servlet.multipart.max-request-size=1024MB
FileController
package com.example.tryRedis.controller;
import static org.springframework.data.mongodb.core.query.Query.*;
import static org.springframework.data.mongodb.gridfs.GridFsCriteria.*;
import com.mongodb.client.gridfs.model.GridFSFile;
import io.swagger.v3.oas.annotations.Parameter;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/file")
public class FileController {
@Autowired
GridFsOperations gridFsOperations;
//上傳文件
@PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Map<String , ObjectId> upload(@Parameter @RequestPart(value = "file") MultipartFile file){
//開始時間
long begin = System.nanoTime();
Map<String,ObjectId> map = new HashMap<>();
try{
InputStream streamForUpload = file.getInputStream();
ObjectId objectId = gridFsOperations.store(streamForUpload,file.getOriginalFilename(),file.getContentType());
//上傳結(jié)束
long end = System.nanoTime();
long time = end-begin;
System.out.println("本次上傳共耗時: "+ time);
System.out.println("上傳成功!文件名: "+file.getOriginalFilename()+". 文件ID: "+objectId);
map.put(file.getOriginalFilename(),objectId);
}catch (Exception e){
e.printStackTrace();
}
return map;
}
//查詢并下載文件
@GetMapping("/download")
public String download(String filename, HttpServletResponse response) throws IOException {
//開始時間
long begin = System.nanoTime();
//查詢文件
GridFSFile result = gridFsOperations.findOne(query(whereFilename().is(filename)));
GridFsResource gridFsResource= gridFsOperations.getResource(result);
String contentType = gridFsResource.getContentType();
System.out.println("contentType: "+contentType);
System.out.println("filename: "+gridFsResource.getFilename());
response.reset();
response.setContentType(contentType);
//注意: 如果沒有下面這行設(shè)置header, 結(jié)果會將文件的內(nèi)容作為響應(yīng)的 body 直接輸出在頁面上, 而不是下載文件
response.setHeader("Content-Disposition","attachment;filename="+filename); //指定下載文件名
ServletOutputStream outputStream = response.getOutputStream();
InputStream is = gridFsResource.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len=is.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
is.close();
outputStream.close();
//下載結(jié)束
long end = System.nanoTime();
long time = end-begin;
System.out.println("本次下載共耗時: "+ time);
return contentType;
}
@DeleteMapping("/delete")
public String deleteFile(@Parameter @RequestParam("filename") String filename){
gridFsOperations.delete(query(whereFilename().is(filename)));
return "delete success";
}
}
測試
上傳

下載
紅色圈內(nèi)點擊download就可以下載啦?;蛘咴诘刂窓谥苯虞斎雔ocalhost:8080/file/download?filename=todo.txt 也可以直接下載文件(這里的todo.txt是我測試的文件,你們填自己上傳的文件名,不要忘了加上后綴名?。?/p>

刪除

上面這些上傳刪除功能測試的時候,大家也可以結(jié)合mongodb的數(shù)據(jù)庫去看看。

上傳的文件類型不限,大小嘛,看你properties文件里設(shè)置的上限是多大了。我拿700MB的文件上傳了也ok,然后在數(shù)據(jù)庫中會被分成很多個塊進行存儲。具體存儲的細節(jié)和原理,網(wǎng)上文檔很多,這兒就不嘮叨嘞。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring中ContextLoaderListener監(jiān)聽詳解
這篇文章主要介紹了Spring中ContextLoaderListener監(jiān)聽詳解,SpringMVC啟動時會啟動WebApplicationContext類型的容器,并且會調(diào)用之前分析的refresh方法,需要的朋友可以參考下2024-01-01
Springboot如何根據(jù)實體類生成數(shù)據(jù)庫表
這篇文章主要介紹了Springboot如何根據(jù)實體類生成數(shù)據(jù)庫表的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
Ribbon單獨使用,配置自動重試,實現(xiàn)負載均衡和高可用方式
這篇文章主要介紹了Ribbon單獨使用,配置自動重試,實現(xiàn)負載均衡和高可用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
Springcloud Stream消息驅(qū)動工具使用介紹
SpringCloud Stream由一個中間件中立的核組成,應(yīng)用通過SpringCloud Stream插入的input(相當(dāng)于消費者consumer,它是從隊列中接收消息的)和output(相當(dāng)于生產(chǎn)者producer,它是發(fā)送消息到隊列中的)通道與外界交流2022-09-09
將Springboot項目升級成Springcloud項目的圖文教程
本文主要介紹了將Springboot項目升級成Springcloud項目,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
netty對proxy protocol代理協(xié)議的支持詳解
這篇文章主要為大家介紹了netty對proxy protoco代理協(xié)議的支持詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07

