我想将带有附加数据的图像从 React.js 发送到 Django 后端。当我使用 FormData() 创建表单数据时,它无法发送数组(因为它将其转换为字符串)。这是我的代码:
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);
Run Code Online (Sandbox Code Playgroud)
当我使用这个时,我得到了这个错误:
{"custom_list":["Incorrect type. Expected pk value, received str."]}
Run Code Online (Sandbox Code Playgroud)
因此,我尝试创建自己的对象以发送到后端,但它无法处理图像数据。代码是:
const formData = {
text: postForm.text,
image: postForm.image,
privacy: postForm.privacy,
custom_list: postForm.customList
}
Run Code Online (Sandbox Code Playgroud)
这给出了以下错误:
{"image":["The submitted data was not a file. Check the encoding type on the form."]}
Run Code Online (Sandbox Code Playgroud)
他们有什么办法可以同时发送列表和图像吗?