我們經常會遇到這樣的場景:上傳/下載文件。
有兩種思路可以解決這個問題:
(1)將文件存儲在服務器的文件系統中;
(2)將文件存儲在數據庫中。
如果我們選擇(2),那么我們可以使用MongoDB GridFS 用於存儲大小超過 16MB 的文件(文檔,壓縮文件,音視頻,軟件)。
一、MongoDB GridFS 介紹
MongoDB GridFS 是一個分布式文件系統,可用於存儲/檢索大小超過 16MB 的文件。
內部實現:將文件分割為一個個 chunk (默認大小為 255KB)進行存儲。
兩個優點:
(1)可以存儲大文件(超過 16MB);
(2)可以從文件的中間位置訪問文件。
二、代碼示例
1 public class FileService { 2 3 // 返回DB 4 private DB getDB() { 5 // ... 6 } 7 8 /* 根據getDB()返回的DB新建一個GridFS實例並返回 9 * 這個GridFS實例用於上傳、下載、刪除、查找文件。 10 */ 11 private GridFS getGridFS() { 12 return new GridFS(getDB(), "自己定義的collection名"); 13 } 14 15 /** 16 * 保存類型為MultipartFile的文件 17 * 18 * @param multipartFile 19 * @throws IOException 20 */ 21 public void saveOne(final MultipartFile multipartFile) throws IOException { 22 saveOne(multipartFile.getInputStream(), multipartFile.getOriginalFilename()); 23 24 } 25 26 /** 27 * 保存類型為java.io.File的文件 28 * 29 * @param file 30 * @throws IOException 31 */ 32 public void saveOne(final File file) throws IOException { 33 saveOne(new FileInputStream(file), file.getName()); 34 } 35 36 public void saveOne(final InputStream in, final String fileName) { 37 GridFSInputFile gridFSInputFile = getGridFS().createFile(in); 38 gridFSInputFile.setFilename(fileName); 39 gridFSInputFile.save(); 40 41 } 42 43 /** 44 * 查詢所有已上傳的文件 45 * 46 * @return 47 */ 48 public Object queryAllFile() { 49 List<GridFSDBFile> result = getGridFS().find((DBObject) null); 50 List<Map<String, Object>> finalResult = new ArrayList<>(); 51 Map<String, Object> map = null; 52 for (GridFSDBFile file : result) { 53 map = new HashMap<>(); 54 map.put("id", ((ObjectId) file.getId()).toHexString()); 55 map.put("fileName", file.getFilename()); 56 map.put("length", file.getLength()); 57 finalResult.add(map); 58 59 } 60 return finalResult; 61 } 62 63 /** 64 * 查詢指定id的文件 65 * 66 * @param hexStringId 67 * 十六進制的id 68 * @return 69 */ 70 public GridFSDBFile queryOne(final String hexStringId) { 71 GridFSDBFile file = getGridFS().findOne(new ObjectId(hexStringId)); 72 return file; 73 74 } 75 76 /** 77 * 刪除給定id的文件 78 * 79 * @param hexStringId 80 */ 81 public void removeOne(final String hexStringId) { 82 getGridFS().remove(new ObjectId(hexStringId)); 83 } 84 }
代碼比較簡單,就不做過多說明了。