3

How to upload files on SharePoint 2013 document library using jQuery? I am stuck with this.

  • Have you tried with REST query? – Mihir Mar 2 '16 at 7:24
1

I also faced this issue a few time ago but, now it has been resolved! Thanks to the post that is given below. I simply followed steps that are mentioned in the post. Do try this out and let me know, however you will definitely get some great help out of it. Thanks!

http://microsoftsharepointsolutions.blog.com/2016/03/10/file-upload-in-sharepoint-list-after-the-items-created-using-jquery/

  • Please avoid just posting a link as an answer. Quote the main aspects of the article as well as the links tend to go down. – Paul Strupeikis Mar 11 '16 at 12:02
  • Unfortunately, this answer is useless to me because the link returns a 504 gateway error. – Omegacron Mar 30 '17 at 17:34
0

You can upload files by using REST queries and JQuery. You can't achieve with JQuery alone. In REST Query following is the basic syntax to add file to any library by using POST method.

http://siteurl+/_api/web/getfolderbyserverrelativeurl('/doclib')/files/add(overwrite=true, url='fileName') 

You will see lot of good documentation here, https://msdn.microsoft.com/en-us/library/office/dn769086.aspx If you are facing any issue while uploading then let us know.

0

I think using JavaScript with REST is a good way of uploading files to SharePoint.

http://geekswithblogs.net/ThorvaldBoe/archive/2014/06/06/how-to-upload-files-to-a-sharepoint-2013-document-library.aspx

http://anthony-verschraegen.blogspot.com/2013/12/sharepoint-2013-js-upload-file-to.html

0

enter image description hereHi Find below Code Snippet Hope this will help you

<input id="addFileButton" type="button" value="Upload" onclick="uploadFile()"/>  


<script type="text/javascript" src="../Style Library/JSFiles/jquery-1.9.1.min.js"></script>

<script type="text/javascript">
'use strict';
 var fileName;
jQuery(document).ready(function () {

    // Check for FileReader API (HTML5) support.
    if (!window.FileReader) {
        alert('This browser does not support the FileReader API.');
    }
});

// Upload the files
function uploadFile() {

    // Get test values from the file input  
    var fileInput = jQuery('#getFile');
   // Get the server URL.
    var serverUrl = _spPageContextInfo.webAbsoluteUrl;

    // Get the local file as an array 
    var getFile = getFileBuffer();
    getFile.done(function (arrayBuffer) {

        // Add the file to the SharePoint Library.
        var addFile = addFileToFolder(arrayBuffer);
        addFile.done(function (file, status, xhr) {
            var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
            getItem.done(function (listItem, status, xhr) {

                // Change the display name and title of the list item.
                var changeItem = updateListItem(listItem.d.__metadata);
                changeItem.done(function (data, status, xhr) {
                    alert('file uploaded');
                     $("#getFile").val("");

                });
                changeItem.fail(onError);
            });
            getItem.fail(onError);
        });
        addFile.fail(onError);
    });
    getFile.fail(onError);

    // Get the local file as an array buffer.
    function getFileBuffer() {
        var deferred = jQuery.Deferred();
        var reader = new FileReader();
        reader.onloadend = function (e) {
            deferred.resolve(e.target.result);
        }
        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }
        reader.readAsArrayBuffer(fileInput[0].files[0]);
        return deferred.promise();
    }

    // Add the file to the file collection in the Shared Documents folder.
    function addFileToFolder(arrayBuffer) {

        // Get the file name from the file input control on the page.
        var parts = fileInput[0].value.split('\\');
        fileName = parts[parts.length - 1];

        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
        "{0}/_api/Web/Lists/getByTitle('TestDocUplode')/RootFolder/Files/Add(url='{1}', overwrite=true)",
            serverUrl, fileName);

        // Send the request and return the response.
        // This call returns the SharePoint file.
        return jQuery.ajax({
            url: fileCollectionEndpoint,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-length": arrayBuffer.byteLength
            }
        });
    }

    // Get the ListItemAllFields property.
    function getListItem(fileListItemUri) {

        // Send the request and return the response.
        return jQuery.ajax({
            url: fileListItemUri,
            type: "GET",
            headers: { "accept": "application/json;odata=verbose" }
        });
    }

    // Change the display name and title of the list item if you want.
    function updateListItem(itemMetadata) {
        var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
            itemMetadata.type, fileName, fileName);

        // Send the request and return the promise.
        // This call not return response content from the server.
        return jQuery.ajax({
            url: itemMetadata.uri,
            type: "POST",
            data: body,
            headers: {
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-type": "application/json;odata=verbose",
                "content-length": body.length,
                "IF-MATCH": itemMetadata.etag,
                "X-HTTP-Method": "MERGE"
            }
        });
    }
}

// Display error messages. 
function onError(error) {
    alert(error.responseText);
}
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.