I have a problem with uploading to my backend with Angular.
this is my component.html
<input type="file" (change)="fileChange($event)" placeholder="Upload file">
This is my component.ts
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData: FormData = new FormData();
formData.append('file', file, file.name);
console.log(formData);
let headers = new Headers();
headers.append('Accept', 'application/json');
const token = localStorage.getItem('token') ? '?token=' + localStorage.getItem('token') : '';
this.http.post('http://localhost:3000/stretch/1' + token, formData, { headers: headers })
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log(data),
error => console.log(error)
);
}
}
This is my backend with NodeJS/express + Multer
var upload = multer({ dest: 'uploads/' }).single('file');
router.post('/1', upload, function (req, res, next) {
var decoded = jwt.decode(req.query.token);
User.findById(decoded.user._id, function (err, user) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err,
});
}
if (!req.file){
return res.status(500).json({
title: 'An error occurred',
error: "No invoice document recieved"
});
}
});
});
And this is what I get on my console:
I am not sure what the problem is or what I am missing I feel like I tried almost anything.
What confuses me though is that when I console.log the formData, it look empty even though I just selected a file. Is that normal?
Your help is much appreciated.