Spring Boot使用GridFS實(shí)現(xiàn)文件的上傳和下載方式
使用GridFS實(shí)現(xiàn)文件的上傳和下載
在這篇博客中,我們將展示如何使用Spring Boot中使用mongodb自帶的文件存儲(chǔ)系統(tǒng)GridFS實(shí)現(xiàn)文件的上傳和下載功能
首先了解一下怎么用命令操作GridFS
安裝mongodb
sudo apt-get install mongodb
安裝完成后找到mongofiles的位置
whereis mongofiles
找到之后進(jìn)入目錄就可以上傳文件了
mongofiles put /home/ubuntu/Desktop/1.jpg
這時(shí)文件就添加成功了,進(jìn)入mongodb查看
mongo show dbs # 發(fā)現(xiàn)多了一個(gè)gridfs use gridfs db.fs.files.find() # 存放文件的一些基本信息 db.fs.chunks.find() # 存放文件二進(jìn)制內(nèi)容,一個(gè)文件有多個(gè)fs.chunks,每個(gè)fs.chunks都有一個(gè),files_id與fs.files中的id相對(duì)應(yīng),形成多對(duì)一的關(guān)系,文件存的時(shí)候分開(kāi)存,取的時(shí)候再合并
使用Spring Boot操作GridFS
引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
controller代碼
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.gridfs.GridFsCriteria.whereFilename;
@RestController
public class ImageController {
@Autowired
private GridFsTemplate gridFsTemplate;
@Autowired
private GridFsOperations operations;
@Autowired
private GridFSBucket gridFSBucket;
@PostMapping("file/upload")
public ImageResponse upload(@RequestParam("file") MultipartFile file) {
DBObject metaData = new BasicDBObject();
// 把時(shí)間戳作為文件名存入mongodb
String fileName = String.valueOf(System.currentTimeMillis());
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
gridFsTemplate.store(inputStream, fileName, "image", metaData);
} catch (IOException e) {
throw new RuntimeException();
}
return new ImageResponse(fileName);
}
@GetMapping(value = "file/download/${fileName}", produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public byte[] getImage(@PathVariable("fileName") String fileName) throws IOException {
if (fileName == null) {
return null;
}
// 根據(jù)文件名查詢(也可以根據(jù)md5值等信息查詢)
GridFSFindIterable result = operations.find(query(whereFilename().is(fileName)));
GridFSFile gridFSFile = result.first();
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//創(chuàng)建gridFsResource,用于獲取流對(duì)象
GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
return IOUtils.toByteArray(gridFsResource.getInputStream());
}
}
加入一個(gè)配置類
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MongoConfig {
@Value("${spring.data.mongodb.database}")
String db;
@Bean
public GridFSBucket getGridFSBucket(MongoClient mongoClient){
MongoDatabase database = mongoClient.getDatabase(db);
GridFSBucket bucket = GridFSBuckets.create(database);
return bucket;
}
}
圖片返回的實(shí)體類
public class ImageResponse implements Serializable {
private String imageName;
public ImageResponse(String imageName) {
this.imageName = imageName;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
}
配置文件
spring:
data:
mongodb:
uri: mongodb://localhost:27017/gridfs
database: gridfs
Spring Boot中使用GridFS
什么是GridFS
GirdFS是MongoDB提供的用于持久化存儲(chǔ)文件的模塊
在GridFS存儲(chǔ)文件是將文件分塊存儲(chǔ),文件會(huì)按照256KB的大小分割成多個(gè)塊進(jìn)行存儲(chǔ),GridFS使用兩個(gè)集合 (collection)存儲(chǔ)文件,一個(gè)集合是chunks, 用于存儲(chǔ)文件的二進(jìn)制數(shù)據(jù);一個(gè)集合是files,用于存儲(chǔ)文件的元數(shù) 據(jù)信息(文件名稱、塊大小、上傳時(shí)間等信息)。
從GridFS中讀取文件要對(duì)文件的各各塊進(jìn)行組裝、合并。
在SpringBoot中使用GridFS
存儲(chǔ)文件
@Autowired
GridFsTemplate gridFsTemplate;
@Test
public void GridFsTest() throws FileNotFoundException {
//選擇要存儲(chǔ)的文件
File file = new File("/Users/xxx/Desktop/xxx.docx");
InputStream inputStream = new FileInputStream(file);
//存儲(chǔ)文件并起名稱
ObjectId objectId = gridFsTemplate.store(inputStream, "面試寶典");
String id = objectId.toString();
//獲取到文件的id,可以從數(shù)據(jù)庫(kù)中查找
System.out.println(id);
}
查找文件
創(chuàng)建GridFSBucket對(duì)象
@Configuration
public class MongoConfig {
@Value("${spring.data.mongodb.database}")
String db;
@Bean
public GridFSBucket getGridFSBucket(MongoClient mongoClient){
MongoDatabase mongoDatabase = mongoClient.getDatabase(db);
GridFSBucket bucket = GridFSBuckets.create(mongoDatabase);
return bucket;
}
}
@Autowired
GridFsTemplate gridFsTemplate;
@Autowired
GridFSBucket gridFSBucket;
@Test
public void queryFile() throws IOException {
String id = "5c1b8fac72884e389ae3df82";
//根據(jù)id查找文件
GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));
//打開(kāi)下載流對(duì)象
GridFSDownloadStream gridFS = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//創(chuàng)建gridFsSource,用于獲取流對(duì)象
GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFS);
//獲取流中的數(shù)據(jù)
String string = IOUtils.toString(gridFsResource.getInputStream(), "UTF-8");
System.out.println(string);
}
刪除文件
//刪除文件
@Test
public void testDelFile() throws IOException {
//根據(jù)文件id刪除fs.files和fs.chunks中的記錄
gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5c1b8fac72884e389ae3df82")));
}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Eclipse Web項(xiàng)目打成war包的方法圖解
當(dāng)Tomcat啟動(dòng)后該壓縮文件自動(dòng)解壓縮,war包方便了web工程的發(fā)布,那么Eclipse中如何將Web項(xiàng)目打成war包呢?下面小編通過(guò)圖文并茂的方式給大家講解下Eclipse Web項(xiàng)目打成war包的方法,一起看看吧2016-08-08
Mybatis Plus 實(shí)現(xiàn)批量插入的示例代碼
本文主要介紹了Mybatis Plus 實(shí)現(xiàn)批量插入的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
詳解Java String字符串獲取每一個(gè)字符及常用方法
這篇文章主要介紹了詳解Java String字符串獲取每一個(gè)字符及常用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
Jetty啟動(dòng)項(xiàng)目中引用json-lib相關(guān)類庫(kù)報(bào)錯(cuò)ClassNotFound的解決方案
今天小編就為大家分享一篇關(guān)于Jetty啟動(dòng)項(xiàng)目中引用json-lib相關(guān)類庫(kù)報(bào)錯(cuò)ClassNotFound的解決方案,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12
SpringMVC修改返回值類型后的消息轉(zhuǎn)換器處理方式
這篇文章主要介紹了SpringMVC修改返回值類型后的消息轉(zhuǎn)換器處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09

