最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Boot使用GridFS實(shí)現(xiàn)文件的上傳和下載方式

 更新時(shí)間:2021年10月23日 10:29:27   作者:我朋友說他好了  
這篇文章主要介紹了Spring Boot使用GridFS實(shí)現(xiàn)文件的上傳和下載方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

使用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í)候分開存,取的時(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ù)庫中查找
   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)));
   //打開下載流對(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)文章

  • 用Java制作用戶登錄界面超詳細(xì)圖文教程

    用Java制作用戶登錄界面超詳細(xì)圖文教程

    很多人學(xué)習(xí)Java的第一個(gè)任務(wù)是使用Java設(shè)計(jì)客戶端登錄界面中,希望我的學(xué)習(xí)方法與總結(jié)能幫助到需要的朋友,這篇文章主要給大家介紹了關(guān)于用Java制作用戶登錄界面的相關(guān)資料,需要的朋友可以參考下
    2024-06-06
  • 基于Apache組件分析對(duì)象池原理的實(shí)現(xiàn)案例分析

    基于Apache組件分析對(duì)象池原理的實(shí)現(xiàn)案例分析

    本文從對(duì)象池的一個(gè)簡(jiǎn)單案例切入,主要分析common-pool2組件關(guān)于:池、工廠、配置、對(duì)象管理幾個(gè)角色的源碼邏輯,并且參考其在Redis中的實(shí)踐,對(duì)Apache組件分析對(duì)象池原理相關(guān)知識(shí)感興趣的朋友一起看看吧
    2022-04-04
  • 淺談Spring如何解決循環(huán)依賴的問題

    淺談Spring如何解決循環(huán)依賴的問題

    這篇文章主要介紹了淺談Spring如何解決循環(huán)依賴的問題,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • Java中ExecutorService和ThreadPoolExecutor運(yùn)行原理

    Java中ExecutorService和ThreadPoolExecutor運(yùn)行原理

    本文主要介紹了Java中ExecutorService和ThreadPoolExecutor運(yùn)行原理,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • Spring超詳細(xì)講解事務(wù)

    Spring超詳細(xì)講解事務(wù)

    Spring事務(wù)的本質(zhì)就是對(duì)數(shù)據(jù)庫事務(wù)的支持,沒有數(shù)據(jù)庫事務(wù),Spring是無法提供事務(wù)功能的。Spring只提供統(tǒng)一的事務(wù)管理接口,具體實(shí)現(xiàn)都是由數(shù)據(jù)庫自己實(shí)現(xiàn)的,Spring會(huì)在事務(wù)開始時(shí),根據(jù)當(dāng)前設(shè)置的隔離級(jí)別,調(diào)整數(shù)據(jù)庫的隔離級(jí)別,由此保持一致
    2022-07-07
  • java 排序算法之希爾算法

    java 排序算法之希爾算法

    這篇文章主要介紹了java 排序算法之希爾排序,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-08-08
  • mybatis-plus中的Enum用法實(shí)例

    mybatis-plus中的Enum用法實(shí)例

    本文主要介紹了mybatis-plus中的Enum用法實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-01-01
  • SpringBoot實(shí)現(xiàn)攔截器、過濾器、監(jiān)聽器過程解析

    SpringBoot實(shí)現(xiàn)攔截器、過濾器、監(jiān)聽器過程解析

    這篇文章主要介紹了SpringBoot實(shí)現(xiàn)攔截器、過濾器、監(jiān)聽器過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • Java實(shí)現(xiàn)手寫乞丐版線程池的示例代碼

    Java實(shí)現(xiàn)手寫乞丐版線程池的示例代碼

    在這篇文章當(dāng)中我們主要介紹實(shí)現(xiàn)一個(gè)非常簡(jiǎn)易版的線程池,深入的去理解其中的原理,麻雀雖小,五臟俱全,感興趣的小伙伴快跟隨小編一起學(xué)習(xí)學(xué)習(xí)吧
    2022-10-10
  • java 最新Xss攻擊與防護(hù)(全方位360°詳解)

    java 最新Xss攻擊與防護(hù)(全方位360°詳解)

    這篇文章主要介紹了java 最新Xss攻擊與防護(hù)(全方位360°詳解),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01

最新評(píng)論

九江县| 景德镇市| 洮南市| 郸城县| 关岭| 仙游县| 怀宁县| 诸城市| 久治县| 香河县| 如皋市| 新沂市| 西乌珠穆沁旗| 长白| 酒泉市| 石景山区| 高青县| 江西省| 交口县| 伊吾县| 刚察县| 余庆县| 兰西县| 额济纳旗| 资中县| 高州市| 赤峰市| 建始县| 蕉岭县| 巴林左旗| 洛川县| 饶平县| 竹溪县| 抚顺市| 金阳县| 怀柔区| 南平市| 修武县| 古浪县| 织金县| 安新县|