问题
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 values.
var item = {
description: 'Some Item',
price : '0.00',
srate : '0.00',
color : 'red',
...
...
}
Now I am asked to add the upload file functionality to my form which, of-course is impossible via JSON and so I am planning on moving to FormData
. So is there any way that I can convert my JS object to FormData
?
回答1:
If you have an object, you can easily create a FormData object and append the names and values from that object to formData.
You haven't posted any code, so it's a general example;
var form_data = new FormData();
for ( var key in item ) {
form_data.append(key, item[key]);
}
$.ajax({
url : 'http://example.com/upload.php',
data : form_data,
processData : false,
contentType : false,
type: 'POST'
}).done(function(data){
// do stuff
});
There are more examples in the documentation on MDN
回答2:
With ES6 and a more functional programming approach @adeneo's answer could looks like this:
function getFormData(object) {
const formData = new FormData();
Object.keys(object).forEach(key => formData.append(key, object[key]));
return formData;
}
And alternatively using .reduce()
and arrow-functions:
getFormData = object => Object.keys(object).reduce((formData, key) => {
formData.append(key, object[key]);
return formData;
}, new FormData());
回答3:
This function adds all data from object to FormData
ES6 version from @developer033:
function buildFormData(formData, data, parentKey) {
if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
Object.keys(data).forEach(key => {
buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key);
});
} else {
const value = data == null ? '' : data;
formData.append(parentKey, value);
}
}
function jsonToFormData(data) {
const formData = new FormData();
buildFormData(formData, data);
return formData;
}
const my_data = {
num: 1,
falseBool: false,
trueBool: true,
empty: '',
und: undefined,
nullable: null,
date: new Date(),
name: 'str',
another_object: {
name: 'my_name',
value: 'whatever'
},
array: [
{
key1: {
name: 'key1'
}
}
]
};
jsonToFormData(my_data)
jQuery version:
function appendFormdata(FormData, data, name){
name = name || '';
if (typeof data === 'object'){
$.each(data, function(index, value){
if (name == ''){
appendFormdata(FormData, value, index);
} else {
appendFormdata(FormData, value, name + '['+index+']');
}
})
} else {
FormData.append(name, data);
}
}
var formData = new FormData(),
your_object = {
name: 'test object',
another_object: {
name: 'and other objects',
value: 'whatever'
}
};
appendFormdata(formData, your_object);
回答4:
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, whileformData.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;
}
回答5:
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) {
}
});
回答6:
Try JSON.stringify function as below
var postData = JSON.stringify(item);
var formData = new FormData();
formData.append("postData",postData );
回答7:
Sorry for a late answer, but I was struggling with this as Angular 2 currently does not support file upload. So, the way to do it was sending a XMLHttpRequest
with FormData
. So, I created a function to do it. I'm using Typescript. To convert it to Javascript just remove data types declaration.
/**
* Transforms the json data into form data.
*
* Example:
*
* Input:
*
* fd = new FormData();
* dob = {
* name: 'phone',
* photos: ['myphoto.jpg', 'myotherphoto.png'],
* price: '615.99',
* color: {
* front: 'red',
* back: 'blue'
* },
* buttons: ['power', 'volup', 'voldown'],
* cameras: [{
* name: 'front',
* res: '5Mpx'
* },{
* name: 'back',
* res: '10Mpx'
* }]
* };
* Say we want to replace 'myotherphoto.png'. We'll have this 'fob'.
* fob = {
* photos: [null, <File object>]
* };
* Say we want to wrap the object (Rails way):
* p = 'product';
*
* Output:
*
* 'fd' object updated. Now it will have these key-values "<key>, <value>":
*
* product[name], phone
* product[photos][], myphoto.jpg
* product[photos][], <File object>
* product[color][front], red
* product[color][back], blue
* product[buttons][], power
* product[buttons][], volup
* product[buttons][], voldown
* product[cameras][][name], front
* product[cameras][][res], 5Mpx
* product[cameras][][name], back
* product[cameras][][res], 10Mpx
*
* @param {FormData} fd FormData object where items will be appended to.
* @param {Object} dob Data object where items will be read from.
* @param {Object = null} fob File object where items will override dob's.
* @param {string = ''} p Prefix. Useful for wrapping objects and necessary for internal use (as this is a recursive method).
*/
append(fd: FormData, dob: Object, fob: Object = null, p: string = ''){
let apnd = this.append;
function isObj(dob, fob, p){
if(typeof dob == "object"){
if(!!dob && dob.constructor === Array){
p += '[]';
for(let i = 0; i < dob.length; i++){
let aux_fob = !!fob ? fob[i] : fob;
isObj(dob[i], aux_fob, p);
}
} else {
apnd(fd, dob, fob, p);
}
} else {
let value = !!fob ? fob : dob;
fd.append(p, value);
}
}
for(let prop in dob){
let aux_p = p == '' ? prop : `${p}[${prop}]`;
let aux_fob = !!fob ? fob[prop] : fob;
isObj(dob[prop], aux_fob, aux_p);
}
}
回答8:
TypeScript version:
static convertModelToFormData(model: any, form: FormData = null, namespace = ''): FormData {
let formData = form || new FormData();
for (let propertyName in model) {
if (!model.hasOwnProperty(propertyName) || model[propertyName] == undefined) continue;
let formKey = namespace ? `${namespace}[${propertyName}]` : propertyName;
if (model[propertyName] instanceof Date) {
formData.append(formKey, this.dateTimeToString(model[propertyName]));
}
else if (model[propertyName] instanceof Array) {
model[propertyName].forEach((element, index) => {
if (typeof element != 'object')
formData.append(`${formKey}[]`, element);
else {
const tempFormKey = `${formKey}[${index}]`;
this.convertModelToFormData(element, formData, tempFormKey);
}
});
}
else if (typeof model[propertyName] === 'object' && !(model[propertyName] instanceof File)) {
this.convertModelToFormData(model[propertyName], formData, formKey);
}
else {
formData.append(formKey, model[propertyName].toString());
}
}
return formData;
}
https://gist.github.com/Mds92/091828ea857cc556db2ca0f991fee9f6
回答9:
You can simply install qs
:
npm i qs
Simply import:
import qs from 'qs'
Pass object to qs.stringify()
:
var item = {
description: 'Some Item',
price : '0.00',
srate : '0.00',
color : 'red',
...
...
}
qs.stringify(item)
回答10:
This method convert a JS object to a FormData :
function convertToFormData(params) {
return Object.entries(params)
.reduce((acc, [key, value]) => {
if (Array.isArray(value)) {
value.forEach((v, k) => acc.append(`${key}[${k}]`, value));
} else if (typeof value === 'object' && !(value instanceof File) && !(value instanceof Date)) {
Object.entries(value).forEach((v, k) => acc.append(`${key}[${k}]`, value));
} else {
acc.append(key, value);
}
return acc;
}, new FormData());
}
回答11:
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;
}
回答12:
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]]
来源:https://stackoverflow.com/questions/22783108/convert-js-object-to-form-data