typescript 如何将整个对象追加到formData

ubof19bj  于 2022-12-24  发布在  TypeScript
关注(0)|答案(1)|浏览(278)

I need to send image list and product data to ASP.net api via formData. I succesfully sended images but now i dont really know how to append whole object. I have seen some ways to do that in JS JSON.stringfy(object) or Object.keys(object).forEach(key => formData.append(key, object[key])); but it doesnt works for me.

  • Angular http服务 *
updateProduct(imageProductVM:ProductImageViewmodel): Observable<any> {
    const formData = new FormData()
    // imageProductVM.product ??

    for (const photo of imageProductVM.files) {
      console.log(photo)
      formData.append('files', photo)
    }
    return this.http.post(this.apiURL + '/product/', formData, {headers:{"ContentType": "multipart/form-data"}})
  }
  • ASP.NET应用程序接口 *

x一个一个一个一个x一个一个二个x

ki0zmccv

ki0zmccv1#

事实上,我忘了说我的产品对象也有嵌套对象。谢谢widoss分享这些信息。
This answer helped me to understand what an object should look like for ASP.net , Here's how it should look in my case:

product.id "*value*"
product.supplierId "*value*"
product.supplierName *value*
product.title "*value*"
product.description "*value*"
product.vendor "*value*"
product.vendorId "*value*"
product.documents[0].id *value*
product.documents[0].url 
product.documents[0].keywords 
product.attributes[0].attributeId *value*
product.attributes[0].attributeName *value*
product.attributes[0].type A
product.attributes[0].value 2

然后我使用以下代码将对象转换为兼容视图:

Object.entries(product).forEach(([key, value], i) => {

  if (typeof value == "object") {
    Object.entries(value as Object).forEach(([nestedKey, nestedValue],  x) => {

      if (typeof nestedValue == "object") {
        Object.entries(nestedValue as Object).forEach(([nestedKey1, nestedValue1]) => {
          formData.append( 'product.'+key+`[${x}].${nestedKey1}`, nestedValue1)
        })

      } else {
        formData.append( 'product.'+key+`[${i}].${nestedKey}`, nestedValue)
      }
    });
  } else {
    formData.append('product.'+key,value)
  }
});

我希望这能帮到一些人

相关问题