Convert JS Object to form data

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

    • Handles nested objects and arrays
    • Handles files
    • Type support
    • Tested in Chrome
    const buildFormData = (formData: FormData, data: FormVal, parentKey?: string) => {
        if (isArray(data)) {
            data.forEach((el) => {
                buildFormData(formData, el, parentKey)
            })
    
        } else if (typeof data === "object" && !(data instanceof File)) {
            Object.keys(data).forEach((key) => {
                buildFormData(formData, (data as FormDataNest)[key], parentKey ? `${parentKey}.${key}` : key)
            })
    
        } else {
            if (isNil(data)) {
                return
            }
    
            let value = typeof data === "boolean" || typeof data === "number" ? data.toString() : data
            formData.append(parentKey as string, value)
        }
    }
    
    export const getFormData = (data: Record) => {
        const formData = new FormData()
    
        buildFormData(formData, data)
    
        return formData
    }
    

    Examples and Tests

    const data = {
        filePhotos: imageArray,
    }
    
    yourAjaxCall({
       ...,
       data: getFormData(data)
    })
    

    Screenshot from Chrome dev tools - Network - Headers:

    const data = {
        nested: {
            a: 1,
            b: ["hello", "world"],
            c: {
                d: 2,
                e: ["hello", "world"],
            }
        }
    }
    
    yourAjaxCall({
       ...,
       data: getFormData(data)
    })
    

提交回复
热议问题