Convert JS Object to form data

前端 未结 18 1876
孤街浪徒
孤街浪徒 2020-11-29 17:22

How can I can convert my JS Object to FormData?

The reason why I want to do this is, I have an object that I constructed out of the ~100 form field valu

相关标签:
18条回答
  • 2020-11-29 17:29

    Maybe you're looking for this, a code that receive your javascript object, create a FormData object from it and then POST it to your server using new Fetch API:

        let myJsObj = {'someIndex': 'a value'};
    
        let datos = new FormData();
        for (let i in myJsObj){
            datos.append( i, myJsObj[i] );
        }
    
        fetch('your.php', {
            method: 'POST',
            body: datos
        }).then(response => response.json())
            .then(objson => {
                console.log('Success:', objson);
            })
            .catch((error) => {
                console.error('Error:', error);
            });
    
    0 讨论(0)
  • 2020-11-29 17:31

    In my case my object also had property which was array of files. Since they are binary they should be dealt differently - index doesn't need to be part of the key. So i modified @Vladimir Novopashin's and @developer033's answer:

    export function convertToFormData(data, formData, parentKey) {
      if(data === null || data === undefined) return null;
    
      formData = formData || new FormData();
    
      if (typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
        Object.keys(data).forEach(key => 
          convertToFormData(data[key], formData, (!parentKey ? key : (data[key] instanceof File ? parentKey : `${parentKey}[${key}]`)))
        );
      } else {
        formData.append(parentKey, data);
      }
    
      return formData;
    }
    
    0 讨论(0)
  • 2020-11-29 17:32

    Here is a short and sweet solution using Object.entries() that will take care of even your nested objects.

    // If this is the object you want to convert to FormData...
    const item = {
        description: 'First item',
        price: 13,
        photo: File
    };
    
    const formData = new FormData();
    
    Object.entries(item).forEach(([key, value]) => {
        formData.append(key, value);
    });
    
    // At this point, you can then pass formData to your handler method
    

    Read more about Object.entries() over here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

    0 讨论(0)
  • 2020-11-29 17:33

    Try obj2fd => https://www.npmjs.com/package/obj2fd

    import obj2fd from 'obj2fd'
    
    let data = {a:1, b:2, c:{ca:1}};
    let dataWithFormData = obj2fd(data);
    //result => [a=>1, b=>2, c=>[ca=>1]]
    
    0 讨论(0)
  • 2020-11-29 17:34

    I reference this from Gudradain's answer. I edit it a little in Typescript format.

    class UtilityService {
        private appendFormData(formData, data, rootName) {
    
            let root = rootName || '';
            if (data instanceof File) {
                formData.append(root, data);
            } else if (Array.isArray(data)) {
                for (var i = 0; i < data.length; i++) {
                    this.appendFormData(formData, data[i], root + '[' + i + ']');
                }
            } else if (typeof data === 'object' && data) {
                for (var key in data) {
                    if (data.hasOwnProperty(key)) {
                        if (root === '') {
                            this.appendFormData(formData, data[key], key);
                        } else {
                            this.appendFormData(formData, data[key], root + '.' + key);
                        }
                    }
                }
            } else {
                if (data !== null && typeof data !== 'undefined') {
                    formData.append(root, data);
                }
            }
        }
    
        getFormDataFromObj(data) {
            var formData = new FormData();
    
            this.appendFormData(formData, data, '');
    
            return formData;
        }
    }
    
    export let UtilityMan = new UtilityService();
    
    0 讨论(0)
  • 2020-11-29 17:36

    I had a scenario where nested JSON had to be serialised in a linear fashion while form data is constructed, since this is how server expects values. So, I wrote a small recursive function which translates the JSON which is like this:

    {
       "orderPrice":"11",
       "cardNumber":"************1234",
       "id":"8796191359018",
       "accountHolderName":"Raj Pawan",
       "expiryMonth":"02",
       "expiryYear":"2019",
       "issueNumber":null,
       "billingAddress":{
          "city":"Wonderland",
          "code":"8796682911767",
          "firstname":"Raj Pawan",
          "lastname":"Gumdal",
          "line1":"Addr Line 1",
          "line2":null,
          "state":"US-AS",
          "region":{
             "isocode":"US-AS"
          },
          "zip":"76767-6776"
       }
    }
    

    Into something like this:

    {
       "orderPrice":"11",
       "cardNumber":"************1234",
       "id":"8796191359018",
       "accountHolderName":"Raj Pawan",
       "expiryMonth":"02",
       "expiryYear":"2019",
       "issueNumber":null,
       "billingAddress.city":"Wonderland",
       "billingAddress.code":"8796682911767",
       "billingAddress.firstname":"Raj Pawan",
       "billingAddress.lastname":"Gumdal",
       "billingAddress.line1":"Addr Line 1",
       "billingAddress.line2":null,
       "billingAddress.state":"US-AS",
       "billingAddress.region.isocode":"US-AS",
       "billingAddress.zip":"76767-6776"
    }
    

    The server would accept form data which is in this converted format.

    Here is the function:

    function jsonToFormData (inJSON, inTestJSON, inFormData, parentKey) {
        // http://stackoverflow.com/a/22783314/260665
        // Raj: Converts any nested JSON to formData.
        var form_data = inFormData || new FormData();
        var testJSON = inTestJSON || {};
        for ( var key in inJSON ) {
            // 1. If it is a recursion, then key has to be constructed like "parent.child" where parent JSON contains a child JSON
            // 2. Perform append data only if the value for key is not a JSON, recurse otherwise!
            var constructedKey = key;
            if (parentKey) {
                constructedKey = parentKey + "." + key;
            }
    
            var value = inJSON[key];
            if (value && value.constructor === {}.constructor) {
                // This is a JSON, we now need to recurse!
                jsonToFormData (value, testJSON, form_data, constructedKey);
            } else {
                form_data.append(constructedKey, inJSON[key]);
                testJSON[constructedKey] = inJSON[key];
            }
        }
        return form_data;
    }
    

    Invocation:

            var testJSON = {};
            var form_data = jsonToFormData (jsonForPost, testJSON);
    

    I am using testJSON just to see the converted results since I would not be able to extract the contents of form_data. AJAX post call:

            $.ajax({
                type: "POST",
                url: somePostURL,
                data: form_data,
                processData : false,
                contentType : false,
                success: function (data) {
                },
                error: function (e) {
                }
            });
    
    0 讨论(0)
提交回复
热议问题