Search code examples
javascriptwordpresscordovaxml-rpc

Upload image to wordpress using Phonegap and Wordpress' XML-RPC


I'm trying to upload an image to WordPress using wp.uploadFile(), but it's not encoded to JPG. I sended a Base64 encoded string, as the api ( http://codex.wordpress.org/XML-RPC_WordPress_API/Media#wp.uploadFile ) says, but when I download the image, it's just text with the string that I sended. I'm getting the photo from Phonegaps API, and I get a base64 encoded string, so I don't think the data is malformed.

By the way, I'm using this library for WordPress API: https://github.com/developerworks/wordpress-xmlrpc-javascript-api

EDIT: here's the code I'm currently using. It's ugly, but I'm just testing.

navigator.camera.getPicture(function(source_image){
var image = document.getElementById('Photo');
image.src = "data:image/jpeg;base64," + source_image;
var hoy = getDate();
photo = wp.uploadFile(1, {
    name: hoy+'.jpg',
    type: 'image/jpg',
    bits: source_image,
    overwrite: false
});
console.log("Photo uploaded!");
}, function(a){console.log(a);alert('imagen no subida');}, cam_options);

Solution

  • This is fragment of the XML payload of the successful "uploadFile" call:

    ...
    <member>
    <name>bits</name>
    <value>
    <base64>...base64-encoded string...</base64>
    </value>
    </member>
    ...
    

    "wordpress-xmlrpc-javascript-api" can generate it, but you need to pass Base64 object (Base64 class is part of the library mimic.js that is used for this API). Here is how it works:

    bits: new Base64( atob(dataURI.split(',')[1]) );
    

    where dataURI is data URI string: "data:image/png;base64,iVBOR......"