【问题标题】:How to send in Angular http post request with data + image?如何使用数据+图像发送Angular http post请求?
【发布时间】:2021-01-13 08:49:13
【问题描述】:

在发布请求中(在 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 ..

});

问题

现在我想发送相同的数据(如示例中所示)以及要保存在服务器上的图像。

附言

我尝试使用 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' 检索和保存图像,但我不知道如何获取 'product' 数据。

【问题讨论】:

  • 如何在 multer 中检索图像?你能发布一些代码吗?

标签: node.js angular express file-upload xmlhttprequest


【解决方案1】:

您可以使用“request.file”访问您在 formData 中添加的图像数据,而您的其他数据将在“request.body”中可用

要在后端上传图片 multer.upload('image') 将被使用。这里的 image 是您在 formdata 中的键。

// 前端

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
});

【讨论】:

  • @RoccoDen91 我没这么说
  • @RoccoDen91 我没有写那个答案。请再看一遍。上面写着谁回答。我只编辑了这个答案中不必要的信息。我帮不了你。请不要ping我。
  • @Khushbu31 正如你所说,我可以使用 req.file 并使用“multer”正确获取和保存图像文件,但我仍然无法获得“产品字段”为了测试它,我试图打印一些东西:console.log("req.body");控制台.log(req.body); //打印这个:[Object: null prototype] { product: '[object Object]' } console.log("req.body.product");控制台.log(req.body.product); //打印这个:[object Object] console.log("req.body.product.code"); console.log(req.body.product.code); //print this: undefined 那么,例如,我怎样才能访问“code”字段?
猜你喜欢
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 2018-04-15
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多