This is my simple code for file upload. I use nodejs with busboy on server and axios with react on client. I select file, submit the form and I see only /upload being handled on the server side:
app.post('/upload', function (req, res) {
console.log("upload"); // we do get here
if (req.busboy) {
// and here
req.busboy.on("file", function (fieldName, fileStream, fileName, encoding, mimeType) {
console.log("on file"); // but never get here
});
return req.pipe(req.busboy);
}
});
But on("file") callback is never called. This is my client code: client code:
<input type="file" onChange={this.getFile} />
getFile(e){
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = (theFile) => {
const data = new FormData();
data.append('file', file);
axios.post("/upload",file);
};
reader.readAsDataURL(file);
}
What can be the problem?
UPDATE: req.body is undefined. I've added these lines:
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false, limit: '50mb'}));
req.body is not null and contains file buffer, but on('file') is not launched yet.
The bug was here:
reader.onloadend = (theFile) => {
const data = new FormData();
data.append('file', file);
axios.post('/upload', data); // <-- I had wrong second argument here!
};