How use GridFSInputFile and GridFS without add file in MongoDB and using Java? -


i developing application when user can add comentary , attach file, it's simple form in ui. in case time optional add file it's obligatory add comentary. in case when user add file in comentary... have code:

    basicdbobject metadata = new basicdbobject();     metadata.put("_id", uuid.randomuuid().tostring());     metadata.put("comentary", "hola que hace");     metadata.put("date", (new date().tostring()));     metadata.put("applicationid", "1111-111");      gridfs gridfs = new gridfs(mongotemplate.getdb(), "noteandfile");     gridfsinputfile gfsfile = gridfs.createfile(file);     gfsfile.put("metadata", metadata);     gfsfile.save(); 

this code works, user doesn't add file have this:

    basicdbobject metadata = new basicdbobject();     metadata.put("_id", uuid.randomuuid().tostring());     metadata.put("comentary", "segundo persist");     metadata.put("date", (new date().tostring()));     metadata.put("applicationid", "2222-222");      gridfs gridfs = new gridfs(mongotemplate.getdb(), "noteandfile");     gridfsinputfile gfsfile = gridfs.createfile();     gfsfile.put("metadata", metadata);     gfsfile.save(); 

but gfsfile.save(); return nul. need use way later obtain list of comments have or not have file attachment.

    basicdbobject allcomentarywithornotfileattach = new basicdbobject();     list<gridfsdbfile> files = gridfs.find(allcomentarywithornotfileattach); 

how can it?

i think thing missing here "empty" input stream there no file attachment. easy fix:

    string mystring = new string();   // empty string      gridfs gridfs = new gridfs(mongotemplate.getdb(),"noteandfile");     gridfsinputfile gfsfile = gridfs.createfile(         new bytearrayinputstream( mystring.getbytes() )     );      basicdbobject meta = new basicdbobject();     meta.put("comments","hi");      gfsfile.put("metadata",meta);     gfsfile.save();      system.out.println(gfsfile.getid());    // gives me _id of object saved 

and when go , in shell:

> db.noteandfile.files.findone() {     "_id" : objectid("55a909057c712d9f488c88e7"),     "chunksize" : numberlong(261120),     "length" : numberlong(0),     "md5" : "d41d8cd98f00b204e9800998ecf8427e",     "filename" : null,     "contenttype" : null,     "uploaddate" : isodate("2015-07-17t13:54:13.837z"),     "aliases" : null,     "metadata" : {             "comments" : "hi"     } } 

of course since "bytestream" here empty, "chunks" collection has no objects associated. should expected.

so can grab object later , add real content it, if , when becomes available.


Comments