Wednesday, 30 July 2014

JQuery-Upload - a few ways to upload a file

I was recently using the magnificent jQuery-File-Upload in a SharePoint 2010 application. I encountered the following scenarios to upload files.

1. Load immediately when the file is selected
This is the easiest option and is pretty much OOTB.
$('#fileupload').fileupload({
                dataType: 'json',
                headers: {
                    Accept: "application/json"
                },
                accept: 'application/json',
                formData: {
                    url: "http://mytargetlocation",
                    title: "myTitle"
                },
                done: function (e, data) {
                    success();
                }
            });

2. Defer load until a button is checked
This code will attach the 'submit' processing to the click event of a button with the ID 'btnSave'

<input id="btnSave" type="submit" >

 $('#fileupload').fileupload({
                dataType: 'json',
                headers: {
                    Accept: "application/json"
                },
                accept: 'application/json',
                formData: {
                    url: "http://mytargetlocation",
                    title: "myTitle"
                },
                add: function (e, data) {
                    data.context = $('#btnSave')
                        .click(function () {
                            data.submit();
                        });
                },
                done: function (e, data) {
                    success();
                }
            });

This approach is great if you are ready for a full postback when the button is clicked.

3. Defer load and load the file in code
This code puts the file in an array, which is used in the 'uploadFile' method to push it to SharePoint

I used this great posting on StackOverflow to find this solution.

var myfiles = [];

 $('#fileupload').fileupload({
                dataType: 'json',
                headers: {
                    Accept: "application/json"
                },
                accept: 'application/json',
                formData: {
                    url: "http://mytargetlocation",
                    title: "myTitle"
                },
                add: function (e, data) {
                    $.each(data.files, function (idx, file) {
                        myfiles.push(file);
                    });
                },
                done: function (e, data) {
                    success();
                }
            });

        function uploadFile() {
            var file = myfiles.pop();
            $('#fileupload').fileupload('send', { files: [file] });
}

No comments:

Post a Comment