3

I am trying to use fetch to upload an image file to my server. Here is my code that I am using:

var formData = new FormData();
    formData.append('photo', {uri: './tempImageStore/image.jpg', name: 'photo', type: 'image/jpg'});

and

       <Button
         onPress={() => fetch('http://localhost:8000/upload', {
           method: 'POST',
           headers: {
             "Accept": "multipart/form-data",
             "Content-Type": "multipart/form-data"
           },
             body: formData
           })
         }
         title={'Upload File'}
       />

However when I run my app and press the Upload File button, I get an error saying:

enter image description here

I am not sure what I am doing wrong or if this is even the proper way to upload photos to a server.

2

1 Answer 1

3

Yes is it possible upload an image only with fetch API.

I was facing the same issue, I solved it with this:

first, please make sure to remove the file// at the beginning of the URL, you could do something like this

const fileURL = "file:///Users/juordergonzalezquinonez/Library/Developer/CoreSimulator/Devices/046E9C13-5D5D-4463-82DD-256501874EBF/data/Containers/Data/Application/839C5E04-46BB-4F9B-BF53-3FDFF639F340/tmp/react-native-image-crop-picker/C07E6B9E-3113-41C2-AD80-A768DF33C263.jpg";
const cleanURL = fileURL.replace("file://", "");

then in the fetch request, make sure that your headers must be like this:

headers: {
  'Accept': 'application/json',
  'Content-Type': 'multipart/form-data;'
},
2
  • I was still able to upload a file with the "file://" prefix.
    – rolznz
    Commented Dec 10, 2018 at 4:09
  • 1
    In Android you need the "file://" prefix and in IOS you must remove the "file://" prefix
    – Banid Azin
    Commented May 6, 2020 at 16:12

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.