Uploading files cross-domain, ajax-style

Uploading files the ‘ajax’-style is something that has been easy to do, as it’s really as easy as targeting a hidden iframe and returning the windows content after load. But when doing these uploads cross-domain, how are you then to get back the response? Well, once again, easyXDM comes to the rescue 🙂

If you want to skip to the result, check out the demo at http://consumer.easyxdm.net/current/example/upload.html!

We’ll start with the consumer, the document that will perform the upload

var rpc = new easyXDM.Rpc({
    remote: "http://remotedomain.com/upload-rpc.html"
}, {
    local: {
        returnUploadResponse: function(response){
            // here we will receive the result from the upload
<form enctype="multipart/form-data" target="upload_target" method="POST" action="http://remotedomain.com/upload.aspx">
    <input type="file" name="file"/>
    <input type="submit" value="Upload File"/>

As you can see, we defined and expose a method that will in the end receive the response from the remote domain.
In the HTML we create a form, and point its action at the remote upload.aspx file (where your upload will be directed) and its target to the upload_target frame that we will soon define.

Now lets take a look at the upload-rpc.html file referred to in the above code

var rpc= new easyXDM.Rpc({}, {
    remote: {
        returnUploadResponse: {}
<iframe name="upload_target" src="about:blank"></iframe>

Doesn’t get much simpler than this 🙂
Here we simply create the provider and in the HTML we create the iframe that will be the target for our upload.

Ok, so far so good, but how do we get the response from the upload document (upload.aspx in our case) back to the consumer?

            status: "success",
            msg: "The upload succeeded!"

As you can see, all this has to do is render Javascript code that uses its parents rpc object to return the response. Dead simple!

To sum it up, the upload goes directly from the consumer document to upload.aspx via POST, and then the response is returned via easyXDM in upload-rpc.html.

This entry was posted in Blog, Examples/How-to's and tagged , . Bookmark the permalink.