MongoDB comes with a distributed file system gridfs, which stores files in blocks. Generally, the storage is sufficient, one example in China is that visual China uses it to store images of hundreds of millions of data. It can be seen that this file system is quite powerful. The following describes how to use spring-data-MongoDB to operate on it. In fact, spring-data-MongoDB does not re-encapsulate gridfs. We can only encapsulate interfaces as needed, the operation of gridfs in the MongoDB Java API is also very simple. 1. get the DB object, 2.new: A gridfsinputfile object, which is equivalent to a file record, containing the file and information related to the file. 3. Call the Save method to save the file. When reading a file, you can query the file based on the file name and ID to find a gridfsdbfile.
Object, and then output the object to a stream or file.
Inject mongodbfactory first
@Autowired private MongoDbFactory mongoDbFactory;
Obtain dB objects
DB db = mongoDbFactory.getDb();
Save the file (fs_name is equivalent to the table name of the gridfs file system and can have multiple tables)
public boolean saveFile(File file, String fileName, String contentType, DBObject metaData) { GridFSInputFile gfsInput; try { gfsInput = new GridFS(db, FS_NAME).createFile(file); gfsInput.setFilename(fileName); gfsInput.setContentType(contentType); gfsInput.setMetaData(metaData); gfsInput.save(); } catch (IOException e) { log.error(e, e); return false; } return true; }
Read files by file name
public GridFSDBFile findFileByName(String fileName){ GridFSDBFile gfsFile ; try { gfsFile = new GridFS(db, FS_NAME).findOne(fileName); } catch (Exception e) { log.error(e, e); return null; } return gfsFile; }
Read files by ID
public GridFSDBFile findFileById(String id){ GridFSDBFile gfsFile ; try { gfsFile = new GridFS(db, FS_NAME).find(new ObjectId(id)); } catch (Exception e) { log.error(e, e); return null; } return gfsFile; }
Output file to outputstream
private boolean writeToOutputStream(OutputStream out, GridFSDBFile gfsFile) { try { gfsFile.writeTo(out); } catch (IOException e) { log.error(e, e); return false; } return true; }