如何将列表追加到FormData? [英] How do I append a list to FormData?
问题描述
我想将带有附加数据的图像从React.js发送到Django后端.当我使用FormData()创建表单数据时,它无法发送数组(因为它已将其转换为字符串).这是我的代码:
I want to send image with additional data from React.js to Django backend. When I used FormData() to create my form data, it could not send the array (because it converted it to string). Here is my code:
let formData = new FormData();
formData.append('text', postForm.text);
formData.append('image', postForm.image, postForm.image.name);
formData.append('privacy', postForm.privacy);
formData.append('custom_list', postForm.customList);
props.createPost(formData);
使用此功能时,出现此错误:
when I used this, I got this error:
{"custom_list":["Incorrect type. Expected pk value, received str."]}
因此,我尝试创建自己的对象发送给后端,但是它无法处理图像数据.代码是:
So, I tried to create my own object to send to backend, but it can't handle image data. The code is:
const formData = {
text: postForm.text,
image: postForm.image,
privacy: postForm.privacy,
custom_list: postForm.customList
}
这给出了以下错误:
{"image":["The submitted data was not a file. Check the encoding type on the form."]}
他们可以同时发送列表和图片吗?
Is their any way I can send both list and image simultaneously?
推荐答案
您可以通过以下方式通过 FormData
发送列表:
You can send a list through FormData
this way:
postForm.customList.forEach(item => {
formData.append('custom_list', item);
});
这将在后端为您提供一个 custom_list
数组.
This will give you a custom_list
array on the backend side.
这篇关于如何将列表追加到FormData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!