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.

zoecarver
  • 5,523
  • 2
  • 26
  • 56
  • In case you won't get it to work: I've had luck with this library. [RN Fetch Blob](https://github.com/wkh237/react-native-fetch-blob). – Viktor Sec May 07 '17 at 00:28
  • I like that library much better, but I have gotten an error with that too: http://stackoverflow.com/questions/43835848/react-native-fetch-blob-undefined-is-not-an-object-evaluating-rnfetchblob-do – zoecarver May 08 '17 at 02:58

1 Answers1

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;'
},
Juorder Gonzalez
  • 1,642
  • 1
  • 8
  • 10