将对象数组转换为formdata

时间:2020-07-30 06:25:33

标签: javascript arrays angular typescript object

我想将对象数组转换为Angular中的Formdata。我的对象数组也可以包含任何键值对和图像。

I,然后必须通过POST API将此表单数据发送到后端(快速)。

[{uid: "", image: File, description: "store", price: "800"}
 {uid: "f9b37f48-cff0-44f1-aa9f-fb9766bde90b", description: "wooden sandals", price: "100"}
 {uid: "dd5adebf-06c6-4d6c-b005-2fcb0a2ca161", description: "blanket", image: File}]

我尝试了很多选择,但能够实现这一目标。

该转换如何完成?

或者,如果我可以直接将此对象数组发送到Angular的POST调用中?

编辑1: image: File是一个File对象: enter image description here

并上传图片:

onUploadImage(imageInput: HTMLInputElement, i, id: string) {
    if(imageInput.files && imageInput.files[0]) {
      this.image = imageInput.files[0]
      if(this.collections[i]['image'] === "" || typeof this.collections[i]['image'] === 'string') this.collections[i]['image'] = this.image
      let result = this.collectionsToAdd.some(item => item['uid'] === id)
      if(result) {
        const index = this.collectionsToAdd.indexOf(this.collectionsToAdd.find(item => item.uid === id))
        this.collectionsToAdd[index]['image'] = this.image
      }
      else {
        const obj = {
          uid: id,
          image: null
        }
        obj.uid = id
        obj.image = this.image
        this.collectionsToAdd.push(obj)
      }

      this.reader.readAsDataURL(imageInput.files[0])
      this.reader.onload = (event) => {
        this.collections[i]['imagePath'] = event.target.result
      }
    }
  }

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以尝试这个。数据就是您的数组。

`

const formData = new FormData()
for(let i = 0; i < Data.length; i += 1) {
     Object.keys(Data[i]).forEach(key => {
          if(key === 'image')
            {
                formData.append(key, JSON.stringify(Data[i][key]))
            } else {
             formData.append(key, Data[i][key])
          }
        
       })
 }`

答案 1 :(得分:0)

我认为最简单的方法是使用多个HTTP请求,这是简单的代码

// your array object
let preBody = [{uid: "", image: File, description: "store", price: "800"},
  {uid: "f9b37f48-cff0-44f1-aa9f-fb9766bde90b", description: "wooden sandals", price: "100"},
  {uid: "dd5adebf-06c6-4d6c-b005-2fcb0a2ca161", description: "blanket", image: File}];

// take a array of form data
let formDataArray: FormData[] = [];

// append each object key - value in formDataArray
preBody.forEach((object, index)=>{
  formDataArray.push(new FormData());
  Object.keys(object).forEach((key)=>{
    formDataArray[index].append(key, object[key]);
  });
});

// send request for each formData
formDataArray.forEach((formData)=>{
  this.http.post('http://localhost/test/text.php', formData).subscribe();
});

注意: 您的数组对象不应包含任何对象或数组。

我希望这会有所帮助