How to convert embed/nested FormGroup to FormData

送分小仙女□ 提交于 2020-06-12 15:29:22

问题


This is my Form Group:

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

I need to convert it to a FormData because I'm uploading images to server (Multer package), however, I'm not sure how to handle address group like a new object inside shopGroup form data. Here is what I'm doing to convert from FormGroup to FormData (address not working):

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

How to make the conversion (Json to FormData) and deal with embed/nested objects like address?


回答1:


Okay, I've found a function for converting JSON objects to 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;
}



回答2:


This should get you started - although, you'll need to make it recursive to deal with nested FormData as you mentioned.

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



回答3:


It should also be possible to create a FormData object from the html-form this way:

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


来源:https://stackoverflow.com/questions/53026879/how-to-convert-embed-nested-formgroup-to-formdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!