runtimeZero runtimeZero - 4 months ago 35
Node.js Question

Multer not saving file as file

I have setup multer as middleware on a route. When that route is hit, multer doesn't download the file. This is what console.log reports:

{ firstname: 'foo',
lastname: 'foo',
username: 'foo10',
password: 'test1234',
file: '/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAAB.....

}


I have the following setup for multer:

var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, '../images/profile');
},
filename: function(req, file, cb) {
cb(null, req.body.username + '.jpeg');
}
});

var upload = multer({storage: storage});

router.post('/auth/signup', upload.single('file'), function(req,res) {
console.log(req.body);
});


So the issue is that instead of saving the file as a file it simply treats it as another key-value pair in the form.

To clarify further, i obtain this image from cordova API:
http://ionicframework.com/docs/v2/native/camera/

import { Camera } from 'ionic-native';

Camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
let base64Image = 'data:image/jpeg;base64,' + imageData;

let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
formData.append("file", base64Image);

xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.open('POST', 'http://localhost:8080/auth/signup', true);
xhr.send(formData);

}, (err) => {
// Handle error
});

Answer

The file data is being uploaded as a Base64 string, which suggests that it's not being uploaded as a proper File form data field. That's why multer treats it as a regular field, and doesn't attempt to save it to a file.

In this answer, some client side code is presented to handle data-URI strings (like base64Image) to the right format to upload to the server.

Comments