I'm uploading an image using multipart/form-data, i want to resize it before storing it anywhere on the disk. I'm using gm to accomplish this but was not able to do it.
<form id="uploadForm" enctype="multipart/form-data" method="post" action="/upload">
<input type="file" name="userFile" />
<input type="submit" value="Upload File" name="submit">
</form>
here is the js file, now i want to resize the image without storing it anywhere on the disk using Imagemagick(gm) module in node. I'm new to node, how can we use the part and resize the image.
var express = require('express');
var multiparty = require("multiparty");
var app = express();
const sharp = require('sharp');
const gm = require('gm').subClass({imageMagick: true});
app.get('/', function(req, res){
res.sendFile('index.html' , { root : __dirname});
});
app.post('/upload', function(req, res){
console.log("in upload")
var count = 0;
var form = new multiparty.Form();
// Errors may be emitted
// Note that if you are listening to 'part' events, the same error may be
// emitted from the `form` and the `part`.
form.on('error', function(err) {
console.log('Error parsing form: ' + err.stack);
});
// Parts are emitted when parsing the form
form.on('part', function(part) {
// You *must* act on the part by reading it
// NOTE: if you want to ignore it, just call "part.resume()"
if (!part.filename) {
// filename is not defined when this is a field and not a file
console.log('got field named dd' + part.name);
// ignore field's content
part.resume();
}
if (part.filename) {
// filename is defined when this is a file
count++;
console.log('got file named ' + part.name);
// console.log(part);
part.on('data', (chunk) => {
console.log("chunck: "+chunk);
var readStream = fs.createReadStream(chunk);
gm(readStream, part.filename)
.resize(240, 240)
.noProfile()
.write('res.png', function (err) {
console.log('Ingm');
if (!err) console.log('resize done');
else
console.log('gm error: '+err);
});
});
// ignore file's content here
part.resume();
}
part.on('error', function (err) {
// decide what to do
});
});
// Close emitted after form parsed
form.on('close', function() {
console.log('Upload completed!');
res.setHeader('text/plain');
res.end('Received ' + count + ' files');
});
// Parse req
form.parse(req);
});