我怎样才能将我的JS对象转换为FormData?
我这样做的原因是,我有一个用~100个表单字段值构造的对象。
var item = {
description: 'Some Item',
price : '0.00',
srate : '0.00',
color : 'red',
...
...
}
现在我被要求将上传文件功能添加到我的表单,当然,通过JSON是不可能的,所以我计划移动到FormData。那么有什么方法可以将我的JS对象转换为FormData呢?
递归地
const toFormData = (f => f(f))(h => f => f(x => h(h)(f)(x)))(f => fd => pk => d => {
if (d instanceof Object) {
Object.keys(d).forEach(k => {
const v = d[k]
if (pk) k = `${pk}[${k}]`
if (v instanceof Object && !(v instanceof Date) && !(v instanceof File)) {
return f(fd)(k)(v)
} else {
fd.append(k, v)
}
})
}
return fd
})(new FormData())()
let data = {
name: 'John',
age: 30,
colors: ['red', 'green', 'blue'],
children: [
{ name: 'Max', age: 3 },
{ name: 'Madonna', age: 10 }
]
}
console.log('data', data)
document.getElementById("data").insertAdjacentHTML('beforeend', JSON.stringify(data))
let formData = toFormData(data)
for (let key of formData.keys()) {
console.log(key, formData.getAll(key).join(','))
document.getElementById("item").insertAdjacentHTML('beforeend', `<li>${key} = ${formData.getAll(key).join(',')}</li>`)
}
<p id="data"></p>
<ul id="item"></ul>
我可能有点晚了,但这就是我创建的将单个对象转换为FormData的方法。
function formData(formData, filesIgnore = []) {
let data = new FormData();
let files = filesIgnore;
Object.entries(formData).forEach(([key, value]) => {
if (typeof value === 'object' && !files.includes(key)) {
data.append(key, JSON.stringify(value) || null);
} else if (files.includes(key)) {
data.append(key, value[0] || null);
} else {
data.append(key, value || null);
}
})
return data;
}
它是如何工作的?
它将转换并返回所有属性,除了您在忽略列表中设置的File对象(第二个参数)。如果有人能告诉我一个更好的方法来确定这将有帮助!)变成一个json字符串使用json .stringify。然后在您的服务器上,您只需要将其转换回JSON对象。
例子:
let form = {
first_name: 'John',
last_name: 'Doe',
details: {
phone_number: 1234 5678 910,
address: '123 Some Street',
},
profile_picture: [object FileList] // set by your form file input. Currently only support 1 file per property.
}
function submit() {
let data = formData(form, ['profile_picture']);
axios.post('/url', data).then(res => {
console.log('object uploaded');
})
}
我仍然有点新的Http请求和JavaScript,所以任何反馈将高度赞赏!
也许你正在寻找这个,一个代码,接收你的javascript对象,从它创建一个FormData对象,然后POST它到你的服务器使用新的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);
});
我参考了古德拉丹的回答。我用Typescript格式编辑了一下。
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();
下面是一个使用Object.entries()的简单而甜蜜的解决方案,它甚至可以处理嵌套对象。
// 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
阅读更多关于Object.entries()在这里- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries