Solution for MongodbException: can't find a chunk! when using GridFS

  
public void insertFileByGridFS(byte[] data, ObjectId id, String filename) throws Exception{
		GridFS gfs = new GridFS(database, "pdf");
		GridFSInputFile gfsFile = gfs.createFile(data.clone());
		gfsFile.setContentType("application/pdf");
		//GridFS will set the parent file id for the chunk id by default.
		//if set the id by setId(new ObjectId()), the file_id of the chunk will be null
		gfsFile.setId(id);
		gfsFile.setFilename(filename);
		gfsFile.save();
		
	}
Please don't explicitly call GridFSInputFile.setId(), otherwise the file_id field of chunk will be null, you can't retrieve the file by GridFSDBFile.findOne(filename) (file name is store in the files collection and link to chunk collection by the file_id)

留言

這個網誌中的熱門文章

Disable ionic's sidemenu content drag to toggle menu

Multiple writable mappings exist for the field. Only one may be defined as writable, all others must be specified read-only.

java.lang.NoClassDefFoundError: org/apache/xerces/jaxp/datatype/XMLGregorianCalendarImpl$Parser