How do I append a list to FormData?

Viewed 4141

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?

2 Answers

You can send a list through FormData this way:

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

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

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

Related