SpringBoot整合MongoDB實現(xiàn)文件上傳下載刪除
本文主要內(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)文章
Springboot接入MyBatisPlus的實現(xiàn)
最近web端比較熱門的框架就是SpringBoot和Mybatis-Plus,這里簡單總結(jié)集成用法,具有一定的參考價值,感興趣的可以了解一下2023-09-09Java替換int數(shù)組中重復數(shù)據(jù)的方法示例
這篇文章主要介紹了Java替換int數(shù)組中重復數(shù)據(jù)的方法,涉及java針對數(shù)組的遍歷、轉(zhuǎn)換、判斷等相關(guān)操作技巧,需要的朋友可以參考下2017-06-06Springboot2.0配置JPA多數(shù)據(jù)源連接兩個mysql數(shù)據(jù)庫方式
這篇文章主要介紹了Springboot2.0配置JPA多數(shù)據(jù)源連接兩個mysql數(shù)據(jù)庫方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09springboot如何配置上傳文件的maxRequestSize
這篇文章主要介紹了springboot如何配置上傳文件的maxRequestSize,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03SpringBoot實現(xiàn)動態(tài)控制定時任務支持多參數(shù)功能
這篇文章主要介紹了SpringBoot實現(xiàn)動態(tài)控制定時任務-支持多參數(shù)功能,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-05-05Springboot中Aspect切面的實現(xiàn)方式(以記錄日志為例)
這篇文章主要介紹了Springboot中Aspect切面的實現(xiàn)方式(以記錄日志為例),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06