How do I append a list to FormData?

丶灬走出姿态 提交于 2021-02-11 14:52:33

问题


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
        }

This gave the following error:

{"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?


回答1:


You can send a list through FormData this way:

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

This will give you an custom_list array on the backend side.




回答2:


Get file from your input, you can use ref

const fileRef = useRef(null)

or

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

then you can simply use this function

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;
})

get base64 string and then simply send that base64 string in json Note : you do not need to specify any other header in axios or fetch, if you are sending base64



来源:https://stackoverflow.com/questions/60754544/how-do-i-append-a-list-to-formdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!