Skip to content

Instantly share code, notes, and snippets.

@RubenPauwels1
Created March 4, 2020 11:05
Show Gist options
  • Save RubenPauwels1/db52705ffa0ef36b7a39407a463d9e93 to your computer and use it in GitHub Desktop.
Save RubenPauwels1/db52705ffa0ef36b7a39407a463d9e93 to your computer and use it in GitHub Desktop.
Upload image to WordPress media library via REST api (React Native)
// Assuming image is coming from the openPicker method from ImagePicker (react-native-image-crop-picker)
// Auth via JWT Token.
export function uploadMedia(image, token) {
return new Promise(async (resolve, reject) => {
var myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${token}`);
myHeaders.append("Content-Type", "multipart/form-data;");
const uriParts = image.path.split('.');
const fileType = uriParts[uriParts.length - 1];
const rand = Math.round(Math.random() * 12345 * Math.random());
const fileName = `image-${image.modificationDate}-${image.size}-${rand}.${fileType}`;
let formdata = new FormData();
formdata.append(
'file',
{
uri: image.path,
name: fileName,
type: image.mime,
}
);
let requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("<YOUR-WP-BASEURL>/wp-json/wp/v2/media", requestOptions)
.then(response => response.text())
.then(result => {
resolve(result);
})
.catch(error => {
reject(error);
});
});
};
@Cchumi
Copy link

Cchumi commented May 10, 2021

Hi thanks for this I have a question about multiple image coming from the library react-native-image-crop-picker.

I try to loop through the image array and append files inside this loop but only the first image was uploaded. Do you know why ?

thanks

@fotomain
Copy link

Hi!
the answer is because:

  1. or you need to call FULL your function in loop
  2. or you need to call formdata.append in loop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment