简体   繁体   中英

How save and query in binary data like images in mongodb with mongoose.js driver and express.js?

Hi my problem is about how save and query images in my mongodb store i have know method basic for inset string , create , update and delete this but when i try save

var UserSchema=new Schema({
    username:String,
    img:{ data: Buffer, contentType: String }
}); //UserSchema

var modelo=mongoose.model('reserv',UserSchema)//model DB

app.post('/upload',function(req,res){
    var img=req.files.imagen

    var imagen=new modelo ({
        username:'name',
        img:{
            data:fs.readFileSync(img.path),
            contentType:img.type,
        }   
    }).save(function(err,docs){
        if(err){
            console.log(err);
        }else{
            console.log('saved');
            res.redirect('/profile')
        }
    }); //return  img saved like binary format 'BJSON' [BSON][1] some thing iVBORw0KGgoAAAANSUhEUgAAB4AA.....

});

So far so good but now when intentento read the image store in database wing binary format becomes virtually impossible with this format that are gigantic characters that compose it and do not know how to decode it more manageable to serve in a view with jade or ejs template engines of express.js please if anyone knows how to decode or compress would be a great help :)

app.get('/profile',function(req,res){

    modelo.findOne({username:'que'},function(err,docs){
        if(err) return err;
        res.render('perfil',{info:docs.img.data})
    });

});

The specific problem is that I need to know how to convert that data in binary format image file to something like a serving or failing to small url.

You should be using GridFS to save your file and then have a separate endpoint for the file. On your page render, you should generate a url that gets that file.

On upload I highly suggest to stream the file directory from the request to the database and on download, stream back directly to the response.

There's some modules that help you with this. express-file-store looks like a good implementation. Since it supports multiple backends, you can change it depending on the configuration(use filesystem on developement and gridfs on production, and easily change it to S3 if by any chance decided to change the backend).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM