Geeks With Blogs
Thorvald Bøe
I found a great code sample on how to upload files to a SP 2013 library using javascript/REST.

The code worked like charm with almost no modifications - just had to change the input control name and the document library name and type. Thanks to Rob Windsor for providing the sample!

Note: Requires html5 support, will not run in older browsers.


Here is the sample code:

function uploadDocument() {
    if (!window.FileReader) {
        alert("This browser does not support the HTML5 File APIs");
        return;
    }

    var element = document.getElementById("uploadInput");
    var file = element.files[0];
    var parts = element.value.split("\\");
    var fileName = parts[parts.length - 1];

    var reader = new FileReader();
    reader.onload = function (e) {
        addItem(e.target.result, fileName);
    }
    reader.onerror = function (e) {
        alert(e.target.error);
    }
    reader.readAsArrayBuffer(file);

    function addItem(buffer, fileName) {
        var call = uploadDocument(buffer, fileName);
        call.done(function (data, textStatus, jqXHR) {
            var call2 = getItem(data.d);
            call2.done(function (data, textStatus, jqXHR) {
                var item = data.d;
                var call3 = updateItemFields(item);
                call3.done(function (data, textStatus, jqXHR) {
                    var div = jQuery("#message");
                    div.text("Item added");
                });
                call3.fail(function (jqXHR, textStatus, errorThrown) {
                    failHandler(jqXHR, textStatus, errorThrown);
                });
            });
            call2.fail(function (jqXHR, textStatus, errorThrown) {
                failHandler(jqXHR, textStatus, errorThrown);
            });
        });
        call.fail(function (jqXHR, textStatus, errorThrown) {
            failHandler(jqXHR, textStatus, errorThrown);
        });
    }

    function uploadDocument(buffer, fileName) {
        var url = String.format(
            "{0}/_api/Web/Lists/getByTitle('Project Documents')/RootFolder/Files/Add(url='{1}', overwrite=true)",
            _spPageContextInfo.webAbsoluteUrl, fileName);
        var call = jQuery.ajax({
            url: url,
            type: "POST",
            data: buffer,
            processData: false,
            headers: {
                Accept: "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "Content-Length": buffer.byteLength
            }
        });

        return call;
    }

    function getItem(file) {
        var call = jQuery.ajax({
            url: file.ListItemAllFields.__deferred.uri,
            type: "GET",
            dataType: "json",
            headers: {
                Accept: "application/json;odata=verbose"
            }
        });

        return call;
    }

    function updateItemFields(item) {
        var now = new Date();
        var call = jQuery.ajax({
            url: _spPageContextInfo.webAbsoluteUrl +
                "/_api/Web/Lists/getByTitle('Project Documents')/Items(" +
                item.Id + ")",
            type: "POST",
            data: JSON.stringify({
                "__metadata": { type: "SP.Data.Project_x0020_DocumentsItem" },
                Year: now.getFullYear()
            }),
            headers: {
                Accept: "application/json;odata=verbose",
                "Content-Type": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "IF-MATCH": item.__metadata.etag,
                "X-Http-Method": "MERGE"
            }
        });

        return call;
    }

    function failHandler(jqXHR, textStatus, errorThrown) {
        var response = JSON.parse(jqXHR.responseText);
        var message = response ? response.error.message.value : textStatus;
        alert("Call failed. Error: " + message);
    }
}
Posted on Friday, June 6, 2014 11:57 AM sharepoint , REST , file upload | Back to top


Comments on this post: How to upload files to a SharePoint 2013 document library using jQuery

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
Hi,
Did you have any luck with upload a file over 300mb? I can get it to upload, but cant get a response. It just hangs.

Thanks
Left by Ash on Dec 31, 2014 5:55 PM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
Sorry, have not tested it with large files. I might have to sometime soon though, I'll update the blog post if I find out something.
Left by Thorvald on Jan 02, 2015 1:44 PM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
what changes are required in order to run on ie9. i know ie 9 is not support HTML 5 but jquery has the feature which runs on all browsers.please assist
Left by RAghav on Jan 09, 2015 8:12 PM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
Both SharePoint 2013 and jQuery runs on IE9, so there shouldnt be any problems here, in theory. I haven't tested it though. Did you try with IE9 and run into problems?
Left by Thorvald on Jan 15, 2015 9:33 AM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
@RAghav, @Thorvald:
You cant get it work in IE9, because the script uses the HTML5 FileReader API. In IE versions IE10+ supports it.
It has nothing to with jquery's browser independence, or sharepoint browser support.
Here you can check wich browsers supports the FileReader API: http://caniuse.com/#feat=filereader
Left by csonthejjas on Mar 20, 2015 11:05 PM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
Thanks for pointing that out, csonthejjas, you are absolutely right! I was not aware of that until now.
Left by Thorvald on Mar 24, 2015 1:53 PM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
Hey, I tried to upload items with this code but sends me this error:

"TypeError: String.format is not a function"

and the line is this

var url = String.format(
"{0}/_api/Web/Lists/getByTitle('Documents')/RootFolder/Files/Add(url='{1}', overwrite=true)",
_spPageContextInfo.webAbsoluteUrl, fileName);

any idea why sends me this error?

Thanks
Left by David Delgado on Jul 22, 2015 10:10 PM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
Hi Thorvald ,

this is awesome. Saved my day. I part accomplished. Can you please let me know how we going to implement multiple file upload?

Ginni.
Left by Ginni on Aug 06, 2015 11:54 AM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
David,
did not have time to check my sample, but apparently the format function is not native. You can create one yourself like this:

http://stackoverflow.com/questions/25227119/javascript-strings-format-is-not-defined

-Thorvald
Left by Thorvald on Sep 01, 2015 11:58 AM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
Ginni,
it is great that you benefited from my post.

I don't have the time to extend my post to cover multiple files, but if I were to, I would start on this line:

var file = element.files[0];

This seems to suggest that the input may have more files. Maybe you would have to set some properties on the input to allow multiple files.

From there you would just have to modify the code to iterate through the selected files and process each individual file separately.

Good luck!

-Thorvald
Left by Thorvald on Sep 01, 2015 12:01 PM

# Getting 403 Forbidden response
Requesting Gravatar...
i think i'm almost getting this but this error sucks... Getting 403 Forbidden response
Left by rendhon on Sep 24, 2015 5:51 PM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
Rendhon,

are you making the call from within a sharepoint hosted app? That would be a possible explanation, as the app is not allowed to contact the host web directly. In such case you would have to use the requestExecutor.

Other than that, I would only suggest to check permissions on the list/library you are calling.

-Thorvald
Left by Thorvald on Sep 30, 2015 3:41 PM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
Does this solution require the use of a SharePoint hosted app ? or can I do this in a webpart page with just javascript / jquery using notepad instead of visual studio ?
Left by Dave on May 06, 2016 11:34 PM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
Hi,
I am trying to make this work with SharePoint 2013 dev site on premise. While I could go with server side code, I desperatly wanted a client side code to do all this job for speedy process, the article is great, gives good insight on what needs to be done but when I host this code in a content editor webpart and try to upload files the rest api part always returns 'failed' , it never succeeds and trying to printing error with alert(JSON.stringify(err)); and no luck it gives empty {} in alert.
could you please point out what might be missing ?
Thanks,
jaya
Left by Jaya Borra on May 12, 2016 4:52 PM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
Hi - having trouble with pdf files. It uploads just fine, but not able to view it in the doc lib.
Left by Vidhya on Dec 07, 2016 2:34 AM

# re: How to upload a html file without file input control into Document Library in Sharepoint 2013
Requesting Gravatar...
Give me the solution.
Left by Divya Singamsetty on Jul 04, 2017 2:17 PM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
is it possible to use this code in Java app to upload file to SharePoint document library
Left by Ran on May 01, 2018 11:17 PM

# re: How to upload files to a SharePoint 2013 document library using jQuery
Requesting Gravatar...
Ran,
no, that is not possible. Although I am not a Java developer, you have to take into account that a Java app (as far as I know) is running server side, and is not authenticated with SharePoint. This code is client side, running in an already authenticated context, that is why you can communicate directly with SharePoint assets like a document library.

It is hard for me to recommend something for you, as I don't know exactly what "Java app" means. Is it a java backend of a web app?

In any case, when accessing SharePoint from external systems, you have various options. For SharePoint OnPremise, you could check out the REST api. For SharePoint Online, check out the SPO SDK.

And for the rest of you guys asking questions, I'm sorry, I just don't have time to maintain this blog anymore, just checking in from time to time.
Left by Thorvald on May 02, 2018 9:34 AM

Your comment:
 (will show your gravatar)


Copyright © Thorvald Bøe | Powered by: GeeksWithBlogs.net