亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

本文主要內(nèi)容

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

1. 基礎(chǔ)命令

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

# 創(chuàng)建數(shù)據(jù)庫
use horse
# 刪除當(dāng)前數(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()
# 查看當(dāng)前數(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()   # 默認(rèn)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 上傳下載刪除

面對疾風(fēng)吧:接合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 {
            // 校驗(yàn)文件信息(文件類型,文件內(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讀取文件并寫入響應(yīng)流,頁面進(jìn)行進(jìn)行相關(guān)操作,可以進(jì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("刪除成功");
    }

}

如果需要實(shí)現(xiàn)在瀏覽器頁面下載此資源的功能,可結(jié)合js進(jìn)行操作(文件類型根據(jù)具體業(yè)務(wù)需求而定)。主要實(shí)現(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實(shí)現(xiàn)文件上傳下載刪除的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot整合MongoDB的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論