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
  • In case you won't get it to work: I've had luck with this library. RN Fetch Blob. Commented May 7, 2017 at 0:28
  • I like that library much better, but I have gotten an error with that too: stackoverflow.com/questions/43835848/… Commented May 8, 2017 at 2:58

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;'
},
Sign up to request clarification or add additional context in comments.

2 Comments

I was still able to upload a file with the "file://" prefix.
In Android you need the "file://" prefix and in IOS you must remove the "file://" prefix

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.