This task may seem straightforward, but I've been struggling with it for hours.
My goal is to upload an image file along with stringified coordinates to crop the image on the server-side.
Below is my client-side code:
var formdata = new FormData();
formdata.append("file", file);
formdata.append("coords", JSON.stringify(coordInfo));
var xhr = new XMLHttpRequest();
if ( xhr.upload ) {
// for handling the progress of the upload
xhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
xhr.onreadystatechange = function(e) {
if ( 4 == this.readyState ) {
console.log(['xhr upload complete', e]);
}
};
xhr.open('post', '/changeProfilePicture', true);
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.send(formdata);
The relevant Express middleware I'm using includes:
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use('/changeProfilePicture', multipartMiddleware);
In my route, I'm simply logging values to check if they were passed correctly:
console.log("req.body.file");
console.log(req.body.file);
console.log("req.body.coords");
console.log(req.body.coords);
console.log("req.body.formdata");
console.log(req.body.formdata);
console.log("req.body");
console.log(req.body);
When checking in Chrome, the request payload
appears as follows:
------WebKitFormBoundary6A5RYri63wa7LqdB
Content-Disposition: form-data; name="file"; filename="monkey_mad.jpg"
Content-Type: image/jpeg
------WebKitFormBoundary6A5RYri63wa7LqdB
Content-Disposition: form-data; name="coords"
{"x":110.13333333333334,"y":103.841059602649,"x2":560,"y2":550.728476821192,"w":449.8666666666667,"h":446.887417218543}
------WebKitFormBoundary6A5RYri63wa7LqdB--
However, on the server-side, only the coords
are being displayed:
17:53:19 web.1 | req.body.file
17:53:19 web.1 | undefined
17:53:19 web.1 | req.body.coords
17:53:19 web.1 | {"x":110.13333333333334,"y":103.841059602649,"x2":560,"y2":550.728476821192,"w":449.8666666666667,"h":446.887417218543}
17:53:19 web.1 | req.body.formdata
17:53:19 web.1 | undefined
17:53:19 web.1 | req.body
17:53:19 web.1 | { coords: '{"x":110.13333333333334,"y":103.841059602649,"x2":560,"y2":550.728476821192,"w":449.8666666666667,"h":446.887417218543}' }
I have tried numerous client-side and server-side variations to make this work. Previously, I used an AJAX XHR Request and busboy on the server side, which resulted in a broken image when retrieved.
For reference, here's the unresolved Stack Overflow question related to that issue: here.
Now, I've switched to a non-AJAX XHR approach and am using connect-multiparty
for parsing, but the problem still persists.