如何将一个列表添加到FormData中?

3

我希望从 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);

当我使用这个时,出现了以下错误:
{"custom_list":["Incorrect type. Expected pk value, received str."]}

所以,我尝试创建自己的对象来发送到后端,但它无法处理图像数据。 代码如下:

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."]}

有没有办法同时发送列表和图片?

1
你的问题是错误的,你需要使用FormData。你应该问“如何将列表附加到FormData?” - dirkgroten
2个回答

9
您可以通过以下方式使用FormData发送列表:
postForm.customList.forEach(item => {
 formData.append('custom_list', item);
});

这将在后端为您提供一个名为custom_list的自定义列表数组。

很奇怪Django在后端处理这样的事情。谢谢! - Fathy

0
从你的输入中获取文件,你可以使用ref。
const fileRef = useRef(null)

或者

const fileRef = React.createRef()

<input 
  type='file'
  label='Upload'
  accept='image/*' 
  ref={fileRef}
/>
const theFile = fileRef.files[0]

那么你可以简单地使用这个函数

function getBase64String(file, cb) {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
        cb(reader.result)
    };
    reader.onerror = function (error) {
        console.log('Error: ', error);
    };
}
let myImageStringToSendInJson = '';
getBase64String(theFile, (result) => {
     myImageStringToSendInJson = result;
})

获取base64字符串,然后简单地将该base64字符串发送到json中。 注意:如果您要发送base64,不需要在axios或fetch中指定任何其他标头。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接