Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
How to attach file in the body while using fetch(for calling api) in react native

Hi I am new to React Native, and I was trying to call my API hosted on Heroku my code is below:

    const path = RNFS.ExternalDirectoryPath + '/newFile.jpg';
    const handleUploadFile = async () => {
    const token = await AsyncStorage.getItem('authtoken')
    const file = await RNFS.readFile(path, "base64");

    let url = `${host}/api/docs/add?card=${value}&number=${myFileId}`;
    console.log(url);
    let imageData = {
        uri: path,
        type: 'image/jpg', //the mime type of the file
        name: 'newFile'
    }
    let formData = new FormData();
    formData.append('file', imageData);
    const response = await fetch(url, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'authtoken': token,
            'Content-Type': 'multipart/form-data'
        },
        body: formData
    });
    const output = await response.json();
    console.log(output);
}

And while programming the server-side I tested my code as enter image description here

But while calling API from react-native I was getting the below error: enter image description here

Please help me in uploading file.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

after you reciving the file as base64 you should convert it to a file and after that you can append it to your formData:

const base64File = await RNFS.readFile(path, "base64");
const blobResult = await fetch(base64File);
const file = new File([blobResult], "newFile",{ type: "image/jpg" });

 const formData = new FormData();
 formData.append('file', file);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!