Reputation: 11
I'm pretty new working with angular and nodejs. I'm trying to upload files to the server and it is working fine, but I want to put the files on specific folder because I don't want to have files together. So this is my code:
const storage = multer.diskStorage({
console.log('carId ' + req.body.carId) //here show undefined
destination: function (req, file, cb) {
cb(null, DIR);
},
filename: function (req, file, cb) {
FILENAME = Date.now() + path.extname(file.originalname);
cb(null, FILENAME);
}
})
const _upload = multer({ storage: storage }).single('file');
exports.upload = async (req, res) => {
try {
_upload(req, res, (err) => {
if (err) {
res.status(500).send(error.message);
}
else {
this.create(req, res); //in this method I can get the carId by doing req.body.carId
}
})
} catch (error) {
res.status(500).send(error.message);
}
}
In the code, with comments I marc where I can get the value and where not. The idea is in the funtion storage get the carId and put the file on /uploads/13 (13) is the value on req.body.carId
Upvotes: 0
Views: 43
Reputation: 11
Here is how I create the data:
const form = new FormData();
for (let i = 0; i < this.fileArray.length; i++) {
form.append('file', this.fileArray[i])
form.append('name', this.fileArray[i].name)
form.append('carId', this.carId)
}
In the service I do this:
uploadFile(data: FormData): Observable<any> {
return this._http.post(`${this.apiUrl}/upload`, data).pipe(catchError(this.handleError));
}
Upvotes: 1