I want to upload images using multer, and resize them on save with sharp.js.
Has anybody tried to use them both? Google is empty
Should be really easy!
var express = require('express')
var multer = require('multer')
var sharp = require('sharp')
var app = express()
app.use(multer({ dest: './uploads/'}))
app.post('/upload', function (req, res, next) {
sharp(req.files['image'].path).resize(200, 200).toBuffer(function (err, buf) {
if (err) return next(err)
// Do whatever you want with `buf`
})
})
Feel free to reopen if you need more help
If anyone is reading this the above code should not be used - taken from the multer docs:
WARNING: Make sure that you always handle the files that a user uploads. Never add multer as a global middleware since a malicious user could upload files to a route that you didn't anticipate. Only use this function on routes where you are handling the uploaded files.
Actually, the code above wouldn't work at all with multer 1.x since it was written for multer 0.x :)
馃憣 even better! thanks
~absolutely 馃憤 ~
edit: aha
Actually, the code above wouldn't work at all with multer 1.x since it was written for multer 0.x :)
Just use Multer as usual with the diskStorage module (refer to the readme for more info), then pass the req.file.path to Sharp
yet not work for me @LinusU
not get any error:
here is my codes:
sharp(req.file.path)
.resize(20,20).toFormat('jpeg')
.toBuffer(function (err,info) {
console.log(info)
})
console.log==<Buffer ff d8 ff db 00 43 00 06 04 05 06 05 04 06 06 05 06 07 07 06 08 0a 10 0a 0a 09 09 0a 14 0e 0f 0c 10 17 14 18 18 17 14 16 16 1a 1d 25 1f 1a 1b 23 1c 16 ... >
if i use the :
app.use(multer({ dest: './uploads/'}))
error>>>>>>app.use() requires a middleware function
But if i use the toFile works.
You need to specify which fields to accept:
app.use(multer({ dest: './uploads/'}))
馃憞
app.use(multer({ dest: './uploads/'}).single('foobar'))
AGA陌N NOT WORK FOR ME:d
app.use(express.static('./public'));
app.use(multer({ dest: './public/uploads/'}).single('avatar'))
const storage=multer.diskStorage({
destination:'./public/uploads',
filename:function(req,file,cb){
cb(null,file.fieldname+"-"+Date.now()+path.extname(file.originalname));
}
});
console.log:
looks like it works. now you have to do something with the buffer - eg. save it to disk
Below code worked for multer 1.4.x
const imagePath = "/....your path to the image..../";
sharp(imagePath).resize(200, 200).toBuffer(function (err, buf) {
if (err) return next(err)
const image = buf.toString('base64');
fs.writeFile(imagePath , image, {encoding: 'base64'}, function(err){
console.log(err);
});
// This will replace your original image with compressed once.
});
Most helpful comment
Should be really easy!