国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

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

發(fā)布時(shí)間:2021-07-17 21:51 來(lái)源:腳本之家 閱讀:0 作者:JackHorse 欄目: 編程語(yǔ)言 歡迎投稿:712375056

目錄

本文主要內容

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

1. 基礎命令

創(chuàng )建的數據名稱(chēng):horse,創(chuàng )建的集合名稱(chēng):blog

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

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

# 創(chuàng  )建指定名稱(chēng)的集合
db.createCollection("blog")
# 刪除指定名稱(chēng)集合
db.blog.drop()
# 查看當前數據庫[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})
# 刪除集合所有數據
db.blog.deleteMan({})


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

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

2. GridFsTemplate使用

2.1引入pom依賴(lài)

        <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
 # 設置文件上傳的大小限制
  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 {
            // 校驗文件信息(文件類(lèi)型,文件內容)
            String originalFilename = file.getOriginalFilename();
            if (StrUtil.isBlank(originalFilename)) {
                return ResponseEntity.badRequest().body("參數錯誤");
            }
            String contentType = file.getContentType();
            if (!CONTENT_TYPES.contains(contentType)) {
                return ResponseEntity.badRequest().body("文件類(lèi)型錯誤");
            }
            InputStream inputStream = file.getInputStream();
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            if (ObjectUtil.isEmpty(bufferedImage)) {
                return ResponseEntity.badRequest().body("文件內容錯誤");
            }

            // 文件重命名
            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("文件上傳異常");
        }
    }


    /**
     * 根據ObjectId讀取文件并寫(xiě)入響應流,頁(yè)面進(jìn)行進(jìn)行相關(guān)操作,可以進(jìn)行文件的下載和展示
     *
     * @param objectId
     */
    @GetMapping("/read")
    public void queryFileByObjectId(@RequestParam("objectId") @NotBlank(message = "ObjectId不能為空") String objectId, HttpServletResponse response) {
        // 根據objectId查詢(xún)文件
        GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(objectId)));
        // 創(chuàng  )建一個(gè)文件桶
        GridFSBucket gridFsBucket = GridFSBuckets.create(mongoTemplate.getDb());
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            if (ObjectUtil.isNotNull(file)) {
                // 打開(kāi)下載流對象
                GridFSDownloadStream fileStream = gridFsBucket.openDownloadStream(file.getObjectId());
                // 創(chuàng  )建girdFsResource,傳入下載流對象,獲取流對象
                GridFsResource gridFsResource = new GridFsResource(file, fileStream);
                // 寫(xiě)入輸出流
                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);
        }
    }

    /**
     * 根據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í)現在瀏覽器頁(yè)面下載此資源的功能,可結合js進(jìn)行操作(文件類(lèi)型根據具體業(yè)務(wù)需求而定)。主要實(shí)現代碼如下所示:

    downloadNotes(noteId) {
      axios({
        url: this.BASE_API + '/admin/mongo/file/query/' + noteId,
        method: 'get',
        responseType: 'arraybuffer',
        params: { type: 'download' }
      }).then(res => {
        // type類(lèi)型可以設置為文本類(lèi)型,這里是pdf類(lèi)型
        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í)現文件上傳下載刪除的詳細內容,更多關(guān)于SpringBoot整合MongoDB的資料請關(guān)注腳本之家其它相關(guān)文章!

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。

国产拍拍拍无码视频免费| 无码福利一区二区三区| 欧亚精品一区三区免费| 国产成人无码18禁午夜福利P| 亚洲午夜无码久久久久小说| 亚洲av片不卡无码av|