Created
March 4, 2020 11:05
-
-
Save RubenPauwels1/db52705ffa0ef36b7a39407a463d9e93 to your computer and use it in GitHub Desktop.
Upload image to WordPress media library via REST api (React Native)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); | |
}); | |
}; |
Hi!
the answer is because:
- or you need to call FULL your function in loop
- 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
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