How to upload and retrieve file in mongodb in spring boot application without using GridFSTemplate? How to upload and retrieve file in mongodb in spring boot application without using GridFSTemplate? mongodb mongodb

How to upload and retrieve file in mongodb in spring boot application without using GridFSTemplate?


I could finally figure out the way to store files without using GridFS in mongodb. First thing you have to note that we have to store byte[] representation of file.

import org.bson.types.Binary;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document;import org.springframework.data.mongodb.core.mapping.Field;@Documentpublic class DemoDocument {    @Id    @Field    private String id;    @Field    private String emailId;    @Field    private String docType;    @Field    private Binary file;}

Make sure your file object is org.bson.types.Binary.Following is my controller code to save object in monogodb.

@PostMapping("/upload")public String singleFileUpload(@RequestParam("file") MultipartFile multipart, @RequestParam("email") String email) {    try {        DemoDocument demoDocument = new DemoDocument();        demoDocument.setEmailId(email);        demoDocument.setDocType("pictures");        demoDocument.setDocument(new Binary(BsonBinarySubType.BINARY, multipart.getBytes()));        mongoTemplate.insert(demoDocument);        System.out.println(demoDocument);    } catch (Exception e) {        e.printStackTrace();        return "failure";    }    return "success";}

You can retrieve this object from mongodb as following.

@PostMapping("/retrieve")public String retrieveFile(@RequestParam("email") String email){    DemoDocument demoDocument = mongoTemplate.findOne(new BasicQuery("{emailId : \""+email+"\", docType : \"pictures\"}"), DemoDocument.class);    System.out.println(demoDocument);    Binary document = demoDocument.getDocument();    if(document != null) {        FileOutputStream fileOuputStream = null;        try {            fileOuputStream = new FileOutputStream(RETRIEVE_FOLDER + "prof_pic.jpg");            fileOuputStream.write(document.getData());        } catch (Exception e) {            e.printStackTrace();            return "failure";        } finally {            if (fileOuputStream != null) {                try {                    fileOuputStream.close();                } catch (IOException e) {                    e.printStackTrace();                    return "failure";                }            }        }    }    return "success";}

Please note this is just sample working code for understanding. It can be written in fully object oriented way keeping design principles in mind.