Upload Media using WordPress.com REST API
I have been trying for days to get this right, but with no luck. I am trying to upload media to a WordPress.com site using the following REST API endpoint:
https://developer.wordpress.com/docs/api/1/post/sites/%24site/media/new/
I am posting a file using a form name of 'media' and I am getting a 200 response back from the server with an array of media items, as the documentation states. However, my single media item in the array has an ID of zero.
It just seems that no matter what I do, I cannot get a file uploaded. And it seems there are no examples of using this endpoint online AT ALL. Please help.
Here is some code:
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var dw = new DataView(ab);
for(var i = 0; i < byteString.length; i++) {
dw.setUint8(i, byteString.charCodeAt(i));
}
// write the ArrayBuffer to a blob, and you're done
return new Blob([ab], {type: mimeString});
}
var url = 'https://public-api.wordpress.com/rest/v1/sites/'+blog.id+'/media/new';
var img = 'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=';
var blob = dataURItoBlob(img);
var data = new FormData();
data.append('media', [blob], 'test-image.gif');
var xhr = new XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader('Authorization', 'BEARER ' + blog.access_token);
xhr.send(data);
var response = JSON.parse(xhr.responseText);
var success = response && response.media && Object.prototype.toString.call(response.media) === '[object Array]' && response.media.length == 1 && response.media[0].id > 0;
I have no idea. I don't even see any public mention of this API endpoint. @mdawaffe, do you have any idea?
I contacted support and got a helpful reply from Joey Kudish, where he said that there is a problem with the endpoint at this time, but the team is working on it. He also pointed me towards testing this on a non WP.com site using the JetPack beta plugin installed, so I am going to give that a try next...
Great! Also check out the WP-API project, which is a candidate for inclusion into WordPress core: https://github.com/WP-API/WP-API
If you want to upload media using WP-API, you should be able to send the data directly to the API as a blob by POSTing the data to /media
Hi - sorry - just saw this.
@bradvin, glad you got in touch with the right people. And yes, WP-API is cool :)