【问题标题】:How do I append a list to FormData?如何将列表附加到 FormData?
【发布时间】:2020-06-30 10:23:02
【问题描述】:

我想将带有附加数据的图像从 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."]}

他们有什么方法可以同时发送列表和图像吗?

【问题讨论】:

  • 你的问题是错误的,你需要使用FormData。您应该问“如何将列表附加到 FormData?”

标签: javascript django reactjs django-rest-framework


【解决方案1】:

您可以这样通过FormData发送列表:

postForm.customList.forEach(item => {
 formData.append('custom_list', item);
});

这将在后端为您提供一个 custom_list 数组。

【讨论】:

    【解决方案2】:

    从你的输入中获取文件,你可以使用 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 字符串,然后简单地以 json 格式发送该 base64 字符串 注意:如果您发送 base64,则不需要在 axios 或 fetch 中指定任何其他标头

    【讨论】:

      猜你喜欢
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 2014-06-13
      • 2020-10-19
      • 2017-12-25
      • 2020-06-23
      • 2023-01-06
      相关资源
      最近更新 更多