SpringBoot整合MongoDB實現(xiàn)文件上傳下載刪除
創(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: 50MB2.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 { // 校驗文件信息(文件類型,文件內(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)流,頁面進行進行相關(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è)務(wù)需求而定)。主要實現(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 = pdfUrllink.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)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. IDEA EasyCode 一鍵幫你生成所需代碼2. Ajax引擎 ajax請求步驟詳細代碼3. Java構(gòu)建JDBC應(yīng)用程序的實例操作4. Spring應(yīng)用拋出NoUniqueBeanDefinitionException異常的解決方案5. ThinkPHP5 通過ajax插入圖片并實時顯示(完整代碼)6. javascript設(shè)計模式 ? 建造者模式原理與應(yīng)用實例分析7. 一篇文章帶你了解JavaScript-對象8. Python使用oslo.vmware管理ESXI虛擬機的示例參考9. IntelliJ IDEA設(shè)置條件斷點的方法步驟10. Express 框架中使用 EJS 模板引擎并結(jié)合 silly-datetime 庫進行日期格式化的實現(xiàn)方法
