javascript
Spring保存文件到MongoDB之GridFS支持
為什么80%的碼農都做不了架構師?>>> ??
問題
Spring上傳來的文件,怎么保存到MongoDB中去類,這里暫時不考慮其他方案來保存文件,如文件系統,FTP等等之類的。假設,已經配好Spring,實現文件上傳,獲取到MultipartFile對象,如果沒有完成,請參考這兩篇文章:《MongoDB在spring中xml傳統配置》和《Spring中formdata方式提交json對象和file之二(改進版)》。
步驟
- 配置Spring支持GridFS
- 通過GridFsOperations保存
配置Spring支持GridFS
配置轉換器
<mongo:mapping-converter id="converter" />配置GridFsTemplate
<bean class="org.springframework.data.mongodb.gridfs.GridFsTemplate"><constructor-arg ref="mongoDbFactory" /><constructor-arg ref="converter" /> </bean>spring-web.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mongo="http://www.springframework.org/schema/data/mongo"xsi:schemaLocation="http://www.springframework.org/schema/data/mongohttp://www.springframework.org/schema/data/mongo/spring-mongo.xsdhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><mongo:mongo-client id="mongoClient" host="localhost" port="27017"/><mongo:db-factory id="mongoDbFactory" mongo-ref="mongoClient"/><mongo:mapping-converter id="converter" /><bean class="org.springframework.data.mongodb.gridfs.GridFsTemplate"><constructor-arg ref="mongoDbFactory" /><constructor-arg ref="converter" /></bean></beans>通過GridFsOperations保存
注解GridFsOperations
@Autowired GridFsOperations operations;使用GridFsOperations
for (MultipartFile multipartFile : multipartFileList) {try {ObjectId objectId = operations.store(multipartFile.getInputStream(), multipartFile.getOriginalFilename());} catch (IOException e) {e.printStackTrace();} }Controller
@Autowired GridFsOperations operations; ... for (MultipartFile multipartFile : multipartFileList) {try {ObjectId objectId = operations.store(multipartFile.getInputStream(), multipartFile.getOriginalFilename());} catch (IOException e) {e.printStackTrace();} } ...**Note:**保存文件到MongoDB成功后,會獲得ObjectId對象,需要將這個對象記住,以便于以后從MongoDB中再次查詢改文件;保存失敗會拋出異常,也是需要關注的。
感受
如果單位有統一的文件系統,還是保存到專門的文件系統比較好,如果需要把數據都集中放在MongoDB中,且文件數據不怎么變動也是可以的。如果通過文件需要更新,就需要通過GridFsOperations先保存文件到MongoDB中成功后,在考慮更新ObjectId,并且刪除原來的ObjectId對應在MongoDB中的文件。
參考: GridFS in Spring Data MongoDB Spring Data MongoDB - Reference Documentation GridFsOperations ObjectId
轉載于:https://my.oschina.net/fxtxz2/blog/1828909
總結
以上是生活随笔為你收集整理的Spring保存文件到MongoDB之GridFS支持的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: django 2.0 url匹配
- 下一篇: word中中文保持正体,英文用斜体的方法