1

I'm trying to use fetch() to perform a media upload in WP Rest API using JS (React Native).

Here's what I've done so far:

fetch('https://www.example.fr/wp-json/wp/v2/media', {
        method: 'post',
        headers: new Headers({
          'Content-Type': 'image/jpeg',
          'Authorization': 'Basic d3GtcmVzdC1sdfGktY2xpZW50Onefepbl9hdh90aWJldA==',
          'Content-Disposition': 'attachment; filename="user-'+userId+'.jpg"'
        }),                
        body: imageBase64Data
      })
      .then(function (response) {
        console.log(response);
      });

imageBase64Data is set like this:

let imageBase64Data = 'data:image/png;base64,'+ imageData;

and imageData is react-native-image-picker response.data: https://github.com/react-community/react-native-image-picker#the-response-object

Here's my issue: the media is created successfully on my WP, but the image is empty (no data, around 15B). So I'm guessing something is messing up with the data I'm sending as the body of my request. But I don't know what.

Any ideas?

enguerranws
  • 8,087
  • 8
  • 49
  • 97

1 Answers1

2

For the record, here's how I finally ended up with this issue, using react-native-fetch-blob module:

 RNFetchBlob.fetch('post', 'https://www.example.fr/wp-json/wp/v2/media', 
      {                    
        'Content-Type': 'image/jpeg',
        'Authorization': 'Basic dqdsfqsdfpbl9hqsdfdsfWJldA==',
        'Content-Disposition': 'attachment; filename="user-'+userId+'.jpg"'
      }

    ,imageUri) // imageUri = RNFetchBlob.wrap(imageUri);
    .then(function (response) {
      console.log(response); // returns a 201 response with id of the attached media
    });    
enguerranws
  • 8,087
  • 8
  • 49
  • 97
  • I'm working with a mobile application right now and I'm trying to send a base64 image to media end-point. Did you do something extra in your code to decode a base64 image? – Fanalea Jan 09 '18 at 12:24
  • No, all is there. – enguerranws Jan 09 '18 at 13:23
  • I see, I will try with custom end-point anyway. I got image uploaded and I got the right size of image but image is not showing up. – Fanalea Jan 09 '18 at 13:45
  • I guess it's because `imageUri` is not a valid image blob. Start a new question to see what's going on. – enguerranws Jan 09 '18 at 14:24