欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot整合MongoDB實現(xiàn)文件上傳下載刪除

 更新時間:2021年05月03日 09:02:16   作者:JackHorse  
這篇文章主要介紹了SpringBoot整合MongoDB實現(xiàn)文件上傳下載刪除的方法,幫助大家更好的理解和學習使用SpringBoot框架,感興趣的朋友可以了解下

本文主要內(nèi)容

  • MongoDB基礎(chǔ)操作命令示例練習
  • MongoDB居于GridFSTemplate的文件上傳、下載、刪除等操作(工作重點使用)

1. 基礎(chǔ)命令

創(chuàng)建的數(shù)據(jù)庫名稱:horse,創(chuàng)建的集合名稱:blog

# 創(chuàng)建數(shù)據(jù)庫
use horse
# 刪除當前數(shù)據(jù)庫[horse]
db.dropDatebase()
# 查看所有數(shù)據(jù)庫
show dbs

 # 設(shè)置用戶的角色和權(quán)限
db.createUser({user:"horse",pwd:"mongo123",roles:[{role:"readWrite",db:"horse"}]})

# 創(chuàng)建指定名稱的集合
db.createCollection("blog")
# 刪除指定名稱集合
db.blog.drop()
# 查看當前數(shù)據(jù)庫[horse]中所有集合
show collections


# 插入文檔
db.blog.insert({"name":"Tom","age":23,"sex":true})
db.blog.insertOne({"name":"Top","age":20,"sex":true})
db.blog.insertMany([{"name":"Jerry","age":22,"sex":false},{"name":"Free","age":21,"sex":true}])


# 更新文檔
db.blog.update({"name":"Top"},{$set:{"name":"TopSun"}},{multi:true})


# 刪除文檔
db.blog.remove({"sex":false}, true)
db.blog.deleteMany({"age":23})
db.blog.deleteOne({"age":22})
# 刪除集合所有數(shù)據(jù)
db.blog.deleteMan({})


# 查詢文檔
db.blog.find().pretty()   # 通過查詢方式(沒有條件,查詢所有)
db.blog.findOne({"name":"Tom"})   # 查詢一個
db.blog.find({"age":{$lt: 23},"name":"Free"}).pretty()   # 默認and連接查詢
db.blog.find({$or:[{"age":{$lt:23}},{"name":"Free"}]}).pretty()   # or連接查詢
db.blog.find({"age":{$lt:23},$or:[{"name":"Free"},{"sex":"false"}]}).pretty() # and和or聯(lián)合使用查詢
db.blog.find().limit(2).skip(1).sort({"age":1}).pretty()   # limit、skip、sort聯(lián)合使用(執(zhí)行順序:sort-> skip ->limit)

# 聚合查詢(參考文檔)
db.blog.aggregate([{$group:{_id:"$age",count:{$sum:1}}}])

2. GridFsTemplate使用

2.1引入pom依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

2.2 配置yml

spring:
  data:
    mongodb:
      host: *.*.*.*
      username: ***
      password: ***
      database: ***
      port: 27017
 # 設(shè)置文件上傳的大小限制
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 50MB

2.3 上傳下載刪除

面對疾風吧:接合HuTool工具包食用更佳?。?!

/**
 * @author Mr.Horse
 * @version 1.0
 * @description: MongoDB的文件上傳、下載、刪除等基本操作(集合HuTool工具庫)
 * @date 2021/4/29 9:53
 */
@Validated
@Controller
@RequestMapping("/mongo")
public class MongoUploadController {

    private static Logger logger = LoggerFactory.getLogger(MongoUploadController.class);

    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/gif", "image/jpeg", "image/jpg", "image/png");

    /**
     * MongoDB文件上傳(圖片上傳)
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResponseEntity<String> fileUpload(@RequestParam("file") MultipartFile file) {
        try {
            // 校驗文件信息(文件類型,文件內(nèi)容)
            String originalFilename = file.getOriginalFilename();
            if (StrUtil.isBlank(originalFilename)) {
                return ResponseEntity.badRequest().body("參數(shù)錯誤");
            }
            String contentType = file.getContentType();
            if (!CONTENT_TYPES.contains(contentType)) {
                return ResponseEntity.badRequest().body("文件類型錯誤");
            }
            InputStream inputStream = file.getInputStream();
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            if (ObjectUtil.isEmpty(bufferedImage)) {
                return ResponseEntity.badRequest().body("文件內(nèi)容錯誤");
            }

            // 文件重命名
            String suffix = FileNameUtil.getSuffix(originalFilename);
            String fileName = IdUtil.simpleUUID().concat(".").concat(suffix);

            // 文件上傳,返回ObjectId
            ObjectId objectId = gridFsTemplate.store(inputStream, fileName, contentType);
            return StrUtil.isBlank(String.valueOf(objectId)) ? ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上傳失敗") : ResponseEntity.ok(String.valueOf(objectId));
        } catch (IOException e) {
            return ResponseEntity.badRequest().body("文件上傳異常");
        }
    }


    /**
     * 根據(jù)ObjectId讀取文件并寫入響應流,頁面進行進行相關(guān)操作,可以進行文件的下載和展示
     *
     * @param objectId
     */
    @GetMapping("/read")
    public void queryFileByObjectId(@RequestParam("objectId") @NotBlank(message = "ObjectId不能為空") String objectId, HttpServletResponse response) {
        // 根據(jù)objectId查詢文件
        GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(objectId)));
        // 創(chuàng)建一個文件桶
        GridFSBucket gridFsBucket = GridFSBuckets.create(mongoTemplate.getDb());
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            if (ObjectUtil.isNotNull(file)) {
                // 打開下載流對象
                GridFSDownloadStream fileStream = gridFsBucket.openDownloadStream(file.getObjectId());
                // 創(chuàng)建girdFsResource,傳入下載流對象,獲取流對象
                GridFsResource gridFsResource = new GridFsResource(file, fileStream);
                // 寫入輸出流
                inputStream = gridFsResource.getInputStream();
                outputStream = response.getOutputStream();
                byte[] bytes = new byte[1024];
                if (inputStream.read(bytes) != -1) {
                    outputStream.write(bytes);
                }
            }
        } catch (IOException e) {
            logger.error("文件讀取異常: {}", e.getMessage());
        } finally {
            IoUtil.close(outputStream);
            IoUtil.close(inputStream);
        }
    }

    /**
     * 根據(jù)ObjectId刪除文件
     *
     * @param objectId
     * @return
     */
    @DeleteMapping("/remove")
    public ResponseEntity<String> removeFileByObjectId(@RequestParam("objectId") @NotBlank(message = "ObjectId不能為空") String objectId) {
        gridFsTemplate.delete(new Query(Criteria.where("_id").is(objectId)));
        return ResponseEntity.ok("刪除成功");
    }

}

如果需要實現(xiàn)在瀏覽器頁面下載此資源的功能,可結(jié)合js進行操作(文件類型根據(jù)具體業(yè)務需求而定)。主要實現(xiàn)代碼如下所示:

    downloadNotes(noteId) {
      axios({
        url: this.BASE_API + '/admin/mongo/file/query/' + noteId,
        method: 'get',
        responseType: 'arraybuffer',
        params: { type: 'download' }
      }).then(res => {
        // type類型可以設(shè)置為文本類型,這里是pdf類型
        const pdfUrl = window.URL.createObjectURL(new Blob([res.data], { type: `application/pdf` }))
        const fname = noteId // 下載文件的名字
        const link = document.createElement('a')
        link.href = pdfUrl
        link.setAttribute('download', fname)
        document.body.appendChild(link)
        link.click()
        URL.revokeObjectURL(pdfUrl) // 釋放URL 對象
      })
    }

以上就是SpringBoot整合MongoDB實現(xiàn)文件上傳下載刪除的詳細內(nèi)容,更多關(guān)于SpringBoot整合MongoDB的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 詳解Spring學習之編程式事務管理

    詳解Spring學習之編程式事務管理

    本篇文章主要介紹了詳解Spring學習之編程式事務管理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-07-07
  • Java SpringBoot自動裝配原理詳解及源碼注釋

    Java SpringBoot自動裝配原理詳解及源碼注釋

    SpringBoot的自動裝配是拆箱即用的基礎(chǔ),也是微服務化的前提。其實它并不那么神秘,我在這之前已經(jīng)寫過最基本的實現(xiàn)了,大家可以參考這篇文章,來看看它是怎么樣實現(xiàn)的,我們透過源代碼來把握自動裝配的來龍去脈
    2021-10-10
  • Springboot接入MyBatisPlus的實現(xiàn)

    Springboot接入MyBatisPlus的實現(xiàn)

    最近web端比較熱門的框架就是SpringBoot和Mybatis-Plus,這里簡單總結(jié)集成用法,具有一定的參考價值,感興趣的可以了解一下
    2023-09-09
  • Java替換int數(shù)組中重復數(shù)據(jù)的方法示例

    Java替換int數(shù)組中重復數(shù)據(jù)的方法示例

    這篇文章主要介紹了Java替換int數(shù)組中重復數(shù)據(jù)的方法,涉及java針對數(shù)組的遍歷、轉(zhuǎn)換、判斷等相關(guān)操作技巧,需要的朋友可以參考下
    2017-06-06
  • Java計算時間差和日期差五種常用示例

    Java計算時間差和日期差五種常用示例

    這篇文章主要給大家介紹了關(guān)于Java計算時間差和日期差五種常用示例的相關(guān)資料,最近工作中遇到需要計算時間差和日期差,搜索了幾種計算時間差和日期差的方法,這里總結(jié)一下,需要的朋友可以參考下
    2023-08-08
  • 基于CXF搭建webService的實例講解

    基于CXF搭建webService的實例講解

    下面小編就為大家?guī)硪黄贑XF搭建webService的實例講解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-11-11
  • Springboot2.0配置JPA多數(shù)據(jù)源連接兩個mysql數(shù)據(jù)庫方式

    Springboot2.0配置JPA多數(shù)據(jù)源連接兩個mysql數(shù)據(jù)庫方式

    這篇文章主要介紹了Springboot2.0配置JPA多數(shù)據(jù)源連接兩個mysql數(shù)據(jù)庫方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • springboot如何配置上傳文件的maxRequestSize

    springboot如何配置上傳文件的maxRequestSize

    這篇文章主要介紹了springboot如何配置上傳文件的maxRequestSize,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • SpringBoot實現(xiàn)動態(tài)控制定時任務支持多參數(shù)功能

    SpringBoot實現(xiàn)動態(tài)控制定時任務支持多參數(shù)功能

    這篇文章主要介紹了SpringBoot實現(xiàn)動態(tài)控制定時任務-支持多參數(shù)功能,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-05-05
  • Springboot中Aspect切面的實現(xiàn)方式(以記錄日志為例)

    Springboot中Aspect切面的實現(xiàn)方式(以記錄日志為例)

    這篇文章主要介紹了Springboot中Aspect切面的實現(xiàn)方式(以記錄日志為例),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06

最新評論