Reputation: 454
I have a problem with my code and I don't see where is the problem.
I have this AJAX part which take a file from a form and an argument and send it to my nodejs server :
var layerID = 2;
var formData = new FormData($("#formid")[0]);
formData.append('layer', layerID);
$.ajax({
url: "http://localhost:3000/file-upload",
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false
});
and i have this part with express which is supposed to receive the file and the argument:
app.use(bodyParser.urlencoded({
extended: false
}))
app.post('/file-upload', function (req, res) {
console.log('params: ' + req.params);
console.log('body: ' + req.body);
console.log('query: ' + req.query);
upload(req, res, function (err) {
if (err) {
errorHandler
return
} else {
successHandler
}
})
})
My problem is that I correctly receive the file but I don't receive the argument 'layer' in my nodejs server.
Upvotes: 0
Views: 59
Reputation: 2459
You can use packages like multiparty
for parsing multipart data in following way. There are other packages as well.
const multiparty = require('multiparty');
// Define POST route
app.post('/file-upload', function (req, res) {
const form = new multiparty.Form();
form.parse(request, async (error, fields, files) => {
if (error) throw new Error(error);
try {
const path = files.file[0].path;
const layer = fields && fields.layer && fields.layer[0]
const buffer = fs.readFileSync(path);
// TODO
return response.status(200).send(data);
} catch (error) {
return response.status(400).send(error);
}
});
}
You can use it this way. You can read from fields.
const formData = new FormData();
formData.append('file', fileObj);
uploadHandler(formData) // this function will make an API call
Now you will be able to get files.file[0]
Upvotes: 1
Reputation: 454
I found the solution, the solution was to simply move my log of req.body in the upload function and call it like that: console.log("layer: " + req.body['layer']);
Upvotes: 0
Reputation: 944083
You are POSTing multipart data, but you only have a body parser for urlencoded
data.
See the documentation for body parser:
This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:
- busboy and connect-busboy
- multiparty and connect-multiparty
- formidable
- multer
Upvotes: 1