Convert JS Object to form data

前端 未结 18 1889
孤街浪徒
孤街浪徒 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:40

    The other answers were incomplete for me. I started from @Vladimir Novopashin answer and modified it. Here are the things, that I needed and bug I found:

    • Support for file
    • Support for array
    • Bug: File inside complex object needs to be added with .prop instead of [prop]. For example, formData.append('photos[0][file]', file) didn't work on google chrome, while formData.append('photos[0].file', file) worked
    • Ignore some properties in my object

    The following code should work on IE11 and evergreen browsers.

    function objectToFormData(obj, rootName, ignoreList) {
        var formData = new FormData();
    
        function appendFormData(data, root) {
            if (!ignore(root)) {
                root = root || '';
                if (data instanceof File) {
                    formData.append(root, data);
                } else if (Array.isArray(data)) {
                    for (var i = 0; i < data.length; i++) {
                        appendFormData(data[i], root + '[' + i + ']');
                    }
                } else if (typeof data === 'object' && data) {
                    for (var key in data) {
                        if (data.hasOwnProperty(key)) {
                            if (root === '') {
                                appendFormData(data[key], key);
                            } else {
                                appendFormData(data[key], root + '.' + key);
                            }
                        }
                    }
                } else {
                    if (data !== null && typeof data !== 'undefined') {
                        formData.append(root, data);
                    }
                }
            }
        }
    
        function ignore(root){
            return Array.isArray(ignoreList)
                && ignoreList.some(function(x) { return x === root; });
        }
    
        appendFormData(obj, rootName);
    
        return formData;
    }
    

提交回复
热议问题