Enable Cross Domain AJax File Upload using jquery file upload plugin

WHAT TO DO FIRST?
1. Enable Cross Domain Ajax Request

2.  Download Blueimp file upload. (I will be using this jquery file upload plugin for my ajax upload).

START

1. First thing first is to initialize your file upload on the client side.

//html
<input id="fileupload" type="file" name="file">


//javascript
jQuery("#fileupload").fileupload({
    url: //url for upload handler,
    datatype: 'json',
    xhrFields: {
        withCredentials: true
    },
    done: function (e, data) {
       //code for done uploading callback
    }
})

As you can see above i set withCredentials to true which will help me for xdomain request

And for the server side (i use php for this one)

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    return YOURRESTRESPONSE('OK');
}

if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) { // handle upload heare}

You should be wondering why there is a blocking for REQUEST METHOD “OPTION” because it will validate if the request is authentic which will depend on the response header YOURRESTRESPONSE is a custom function i created for modified header response. The functin contains modifying

Access-Control-Allow-Credentials your_other_origin
Access-Control-Allow-Origin  'true'
Access-Control-Allow-Methods  'POST PUT DELETE GET OPTIONS'

Above Properties are stated on Enable Cross Domain Ajax Request

If YOURRESTRESPONSE is success. Blueimp ajax upload will automatically send another request for file upload.
And after that your upload file should be working.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s