FormData sends string value instead of video file in react-native

Viewed 1126

I am trying to upload my video to backend server using FormData. But when uploading video file, I am getting string value instead of video file in backend. Thank you

const formData = new FormData();
formData.append('dare_id', `${encrypted_id}`);
formData.append(
  'video',
  Platform.OS === 'android'
    ? uri                                 //local video file uri
    : uri.replace('file://', ''),        //local video file uri
);

fetch(UPLOAD_URL, {
  method: 'POST',
  headers: {
    'Content-Type': 'multipart/form-data',
    Authorization: `Bearer ${token}`,
    Accept: 'application/json',
  },
  body: formData,
})
  .then(res => res.json())
  .then(responseJson => {
    console.log(responseJson);
  })
  .catch(error => {
    console.log(error, ' error uploading');
  });
2 Answers

For uploading file you must insert file type and the file name as well. Here is he code:

let formData=new FormData();
formData.append({uri:yourNormalizedUri,type:”I dont know exactly but it should be video/mp4 google it”, name:”video.mp4”});

Try it again without the Content-Type header. Here is an article: https://muffinman.io/uploading-files-using-fetch-multipart-form-data/

I've had this problem before with sending files with Axios the same way. The library is smart enough to set the headers correctly unless you add them. I suspect you are seeing an error related to the boundary setting which must be exact.

So rather than explicitly setting the header, try relying on the default, and allow fetch (or axios) to set the headers correctly based on the inclusion of the file type for one of the form fields.

Related