在发布请求中(以Angular为单位),我通常使用“对象”发送数据(例如“产品”数据):
product: any = {}; // filled of proprieties (code, barcode, name, description...)
,然后在请求中传递它:
return this.http
.post<any>( Url , product)
.pipe(catchError(this.errorHandler));
使用ExpressJS,我可以轻松地检索属性'req.body。<<属性>>':
router.post("/newProduct", function (req, res, next) {
const code = req.body.code;
const barcode = req.body.barcode;
const nameProduct = req.body.name;
const description = req.body.description;
//.. here other code - mySql to insert data in the DB ..
});
问题
现在,我想发送相同的数据(如示例中所示)以及要保存在服务器上的图像。
PS
我尝试使用FormData:
var formData = new FormData();
formData.append('image', imageFile);
formData.append('product', product);
return this.http
.post<any>(this.newProductUrl, formData )
.pipe(catchError(this.errorHandler));
因此,在后端,我可以使用npm包“ multer”来检索和保存图像,但是我不知道如何获取“产品”数据。
答案 0 :(得分:0)
您可以使用'request.file'访问在formData中添加的图像数据,而其他数据将在'request.body'中可用
要在后端中上传图像,将使用multer.upload('image')。图像是表单数据中的关键。
//前端
var formData = new FormData();
formData.append('image', imageFile);
formData.append('product', product);
//后端
var upload = multer({ dest: 'uploads/' }) // uploads your destination folder
app.post('/profile', upload.single('image'), function (req, res, next) {
// req.file is the `image` file
// req.body will hold the text fields, if there were any
});