简体   繁体   中英

How to resize image with sharp then upload with multer in nodejs

I'm developing a feature to allow user upload image to mongodb with nodejs :

  • My Problem :

    Get image file from user's request and do 2 task: store current image to mongodb with collection name "Origin_image" for example and resize current image and store to mongodb with collection name "Thumbnail_image"

  • My solution so far:

    I just only store success original image by using multer-gridfs-storage and multer like code below

    const multer = require('multer'); const GridFsStorage = require('multer-gridfs-storage');

    const multer = require('multer'); const GridFsStorage = require('multer-gridfs-storage');

      let storageFS = new GridFsStorage({ db: app.get("mongodb"), file: (req, file) => { return new Promise((resolve, reject) => { crypto.randomBytes(16, (err, buf) => { if (err) { return reject(err); } const filename = file.originalname; const fileInfo = { filename: filename, bucketName: 'images' }; resolve(fileInfo); }); }); } }); var upload = multer({ storage: storageFS }).single('image'); exports.uploadImage = async function (req, res) { try { upload(req, res, function (err) { if (err) { return res.send(err) } res.json({ status: true, filePath: req.file.originalname }); }); } catch (error) { res.send(error); } } 

Does anyone have any idea to solve my problem? thanks !

If you are using Angular on your frontend, let the end user handle the image resizing so that your server does not have to deal with the overhead. I am currently using ng2-img-max to resize images. You can initiate the resize as on file change.

I also wanted to have thumbnails and then the original, but this caused a huge issue in performance when resizing both and then again how to link them as GridFs stores them before you can do anything with them and all you have left is the response. So save yourself some time. Only resize once, to your limited size for the user and then for displaying thumbnail images, use sharp with custom query params to display the size you want.

Good luck and happy coding.

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