如何将嵌入/嵌套的FormGroup转换为FormData

时间:2018-10-27 22:37:54

标签: javascript angular forms typescript multipartform-data

这是我的表单组:

this.shopGroup = this.fb.group({
  _user: [''],
  name: ['', Validators.compose([Validators.required, Validators.maxLength(60)])],
  url_name: [''],
  desc: ['', Validators.compose([Validators.required, Validators.maxLength(600)])],
  photos: [''],
  currency: ['Real'],
  language: ['Português do Brasil'],
  address: this.fb.group({
    zipcode: ['', Validators.compose([Validators.required, Validators.pattern('[0-9]{5}[\-]?[0-9]{3}')])],
    street: ['', Validators.compose([Validators.required, Validators.maxLength(70)])],
    number: [null, Validators.compose([Validators.required, Validators.max(99999)])],
    complement: ['', Validators.maxLength(30)],
    district: ['', Validators.compose([Validators.required, Validators.maxLength(60)])],
    state: ['', Validators.required],
    city: ['', Validators.compose([Validators.required, Validators.maxLength(70)])]
  }),
  status: [true],
  created_at: [new Date()],
  updated_at: [new Date()]
});

我需要将其转换为FormData,因为我正在将图像上传到服务器(Multer程序包),但是,我不确定如何像处理address中的新对象一样处理shopGroup组表格数据。 这是我从FormGroup转换为FormData(地址不起作用)的工作:

const shopData: any = new FormData();
shopData.append('name', shopGroup.get('name').value);
shopData.append('zipcode', shopGroup.get('address').get('zipcode').value);
...

如何进行转换(从Json到FormData)并处理诸如address之类的嵌入/嵌套对象?

3 个答案:

答案 0 :(得分:2)

好的,我找到了一个将JSON对象转换为FormData的函数:

convertJsontoFormData(jsonObject: Object, parentKey, carryFormData: FormData): FormData {

    const formData = carryFormData || new FormData();
    let index = 0;

    for (var key in jsonObject) {
        if (jsonObject.hasOwnProperty(key)) {
            if (jsonObject[key] !== null && jsonObject[key] !== undefined) {
                var propName = parentKey || key;
                if (parentKey && this.isObject(jsonObject)) {
                    propName = parentKey + '[' + key + ']';
                }
                if (parentKey && this.isArray(jsonObject)) {
                    propName = parentKey + '[' + index + ']';
                }
                if (jsonObject[key] instanceof File) {
                    formData.append(propName, jsonObject[key]);
                }  else if (jsonObject[key] instanceof FileList) {
                    for (var j = 0; j < jsonObject[key].length; j++) {
                        formData.append(propName + '[' + j + ']', jsonObject[key].item(j));
                    }
                } else if (this.isArray(jsonObject[key]) || this.isObject(jsonObject[key])) {
                    this.convertJsontoFormData(jsonObject[key], propName, formData);
                } else if (typeof jsonObject[key] === 'boolean') {
                    formData.append(propName, +jsonObject[key] ? '1': '0');
                } else {
                    formData.append(propName, jsonObject[key]);
                }
            }
        }
        index++;
    }
    return formData;
}
isArray(val) {
    const toString = ({}).toString;
    return toString.call(val) === '[object Array]';
}

isObject(val) {
    return !this.isArray(val) && typeof val === 'object' && !!val;
}

答案 1 :(得分:1)

这应该使您入门-尽管,您需要使它像您提到的那样递归地处理嵌套的FormData。

const shopData = Object.keys(this.shopGroup.value).map(function (key) {
  return encodeURIComponent(key) + '=' + encodeURIComponent(form.value[key]);
}).join('&');

答案 2 :(得分:0)

也应该可以通过以下方式从html表单创建FormData对象:

const formData = new FormData(<HTMLFormElement>document.getElementById('formId'));