SharePoint 2013 file upload with Jquery

sharepoint 2013 upload file to document library using jquery
how to upload file in document library in sharepoint using rest api jquery
upload file to sharepoint online programmatically
upload file to sharepoint using postman
upload multiple files to sharepoint list item using rest api
upload file to sharepoint using rest api java
sharepoint 2010 upload file to document library using jquery
programmatically upload file to sharepoint

I am currently developing a page which users will be able to upload from their local machines files to a sharepoint 2013 server.

Currently I have managed to experiment with the ajax calls and use the rest api for creating simple .txt files and additional folders.

The problem I am facing is a response I am getting when trying to upload a .doc file or any other file that is using an arrayBuffer as the data.

Here is my code (which again is working is the data passed is a simple string:

url = "http://temp-sharepoint/_api/Web/GetFolderByServerRelativeUrl('Documents')/files/add(overwrite=true,url='"+fileName+"')";

            jQuery.ajax({
                url: url,
                type: "POST",
                data: arrayBuffer,
                processData: false,
                headers: {
                    "Accept": "application/json; odata=verbose",
                    "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                     "content-length": arrayBuffer.byteLength
                },
               success: doSuccess,
                error: onError
            });

The code above will result in a response of

[object Error]{description: "The paramet...", message: "The paramet...", name: "Error", number: -2147024809, stack: "Error: The ..."}

which is "The Parameter is incorrect."

Again if data is "Test" the file is being created with no problems.

I am quite new to sharepoint and I would appreciate if someone can point me to a possible solution.

Thanks.


How are you reading file into buffer check if it contains proper data while debugging using browser debugger

Sample code for uploading file

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
        }
    });        
}

SharePoint 2013 file upload with Jquery, How are you reading file into buffer check if it contains proper data while debugging using browser debugger. Sample code for uploading file function  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')


If you want to upload a lot and you are using nintex (very similar to jquery)

  NWF$("#getFile").on('change', function () {
    var files = this.files;
    for (var i = 0; i < files.length; i++) {
        // IFFY to save the current index
        (function (x) {
            var file = files[x];
            lastFileName = file.name;
            var fileName = Date.now() + file.name;
            var getFileBuffer = function (file) {
                //alert('in getFileBuffer');
                var deferred = NWF$.Deferred();
                var reader = new FileReader();
                reader.onload = function (e) {
                    deferred.resolve(e.target.result);
                }
                reader.onerror = function (e) {
                    deferred.reject(e.target.error);
                }
                reader.readAsArrayBuffer(file);
                return deferred.promise();
            };


            getFileBuffer(file).then(function (buffer) {
                //alert(buffer);
                NWF$.ajax({
                    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(1)/AttachmentFiles/add(FileName='" + fileName + "')",
                    method: 'POST',
                    body: "Contents of file",
                    data: buffer,
                    processData: false,
                    headers: {
                        "ACCEPT": "application/json; odata=verbose",
                        "content-type": "application/json; odata=verbose",
                        "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
                        // "content-length": buffer.byteLength
                    }, //end headers
                    success: function (data) {
                        ++indexFile;
                        console.log(data);
                        var fileUrl = _spPageContextInfo.siteAbsoluteUrl + data.d.ServerRelativeUrl;
                        NWF$('#displayFiles tr:last').after('<tr><td><a class="fileLink" href="' + fileUrl + '">' + lastFileName + '</a></td><td><a class="removeHyper">מחיקה &times</a></td></tr>');
                        filesItems.push(_spPageContextInfo.siteAbsoluteUrl + data.d.ServerRelativeUrl);
                        NWF$('#' + filesList).text(converAddressToString(filesItems))
                    },
                    error: function (data) {
                        console.log("err " + data.d);
                    }
                });
            })
        })(i)

Upload a file by using the REST API and jQuery, I found a great code sample on how to upload files to a SP 2013 library using webAbsoluteUrl, fileName); var call = jQuery.ajax({ url: url, type:  Code example 1: Upload a file across SharePoint domains by using the REST API and jQuery. The following code example uses the SharePoint REST API and jQuery AJAX requests to upload a file to the Documents library and to change properties of the list item that represents the file. The context for this example is a SharePoint-hosted add-in that uploads a file to a folder on the host web.


//Try using this if you need to upload multiple items too with file type and size restrictions.

var appWebUrl, hostWebUrl;

jquery(document).ready(function () {

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

    // Get the add-in web and host web URLs.
    appWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
});

// Upload the file.
// You can upload files up to 2 GB with the REST API.
function uploadFile() {

    // Define the folder path for this example.
    var serverRelativeUrlToFolder = '/shared documents';

    // Get test values from the file input and text input page controls.
    // The display name must be unique every time you run the example.
    var fileInput = jQuery('#getFile');
    var newName = jQuery('#displayName').val();

    // Initiate method calls using jQuery promises.
    // Get the local file as an array buffer.
    var getFile = getFileBuffer();
    getFile.done(function (arrayBuffer) {

        // Add the file to the SharePoint folder.
        var addFile = addFileToFolder(arrayBuffer);
        addFile.done(function (file, status, xhr) {

            // Get the list item that corresponds to the uploaded file.
            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 and updated');
                });
                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('\\');
        var fileName = parts[parts.length - 1];

        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
            "{0}/_api/sp.appcontextsite(@target)/web/getfolderbyserverrelativeurl('{1}')/files" +
            "/add(overwrite=true, url='{2}')?@target='{3}'",
            appWebUrl, serverRelativeUrlToFolder, fileName, hostWebUrl);

        // 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 list item that corresponds to the file by calling the file's ListItemAllFields property.
    function getListItem(fileListItemUri) {

        // Construct the endpoint.
        // The list item URI uses the host web, but the cross-domain call is sent to the
        // add-in web and specifies the host web as the context site.
        fileListItemUri = fileListItemUri.replace(hostWebUrl, '{0}');
        fileListItemUri = fileListItemUri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');

        var listItemAllFieldsEndpoint = String.format(fileListItemUri + "?@target='{1}'",
            appWebUrl, hostWebUrl);

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

    // Change the display name and title of the list item.
    function updateListItem(itemMetadata) {

        // Construct the endpoint.
        // Specify the host web as the context site.
        var listItemUri = itemMetadata.uri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
        var listItemEndpoint = String.format(listItemUri + "?@target='{0}'", hostWebUrl);

        // Define the list item changes. Use the FileLeafRef property to change the display name. 
        // For simplicity, also use the name as the title.
        // The example gets the list item type from the item's metadata, but you can also get it from the
        // ListItemEntityTypeFullName property of the list.
        var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
            itemMetadata.type, newName, newName);

        // Send the request and return the promise.
        // This call does not return response content from the server.
        return jQuery.ajax({
            url: listItemEndpoint,
            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);
}

// Get parameters from the query string.
// For production purposes you may want to use a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
    var params = document.URL.split("?")[1].split("&amp;");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve) return singleParam[1];
    }
}

How to upload files to a SharePoint 2013 document library using , Upload Single/Multiple file by using the REST API and jQuery SharePoint 2013. Here you can find how to upload single/multiple file in  Preparing your JS files for SP2013: Modify JQuery and all additional libraries to be in the SharePoint namespace. To add a file into a namepsace surround it with this code: // Example for JQuery, replace jquery with your library name function $_global_jquery() { // Library code goes here } $_global_jquery();


Upload Single/Multiple file by using the , In this post we will see how to upload a file to Document library to a specific folder path using rest api in SharePoint online and SharePoint 2013. 4) Upload the jquery-3.1.1.js(use can you the latest version of Jquery) to one  Navigate to your SharePoint 2013 site. From this page, select Site Actions | Edit Page. Edit the page, go to the Insert tab in the Ribbon and click Web Part option. In the Web Parts picker area, go to the Media and Content category, select the Script Editor Web Part and press the Add button.


Upload a file into document library using REST API in SharePoint , Howto upload a file into a SharePoint Library using SpRestLib. The upload() method accepts an ArrayBuffer from both Node.js and client  1) Create a Document Library ( SampleDocuments) with 2 columns ( Column1 and Column2) .Create a folder ( Folder1) in that. 2) Copy the below script and to a notepad and save the file with name FileUploadScript.js. 1.


Uploading a file to a SharePoint library using JavaScript · SpRestLib, will see how to upload a file in the library using the REST API and jQuery. to Get Document Libraries in a SharePoint 2013 Using REST API. Open SharePoint Designer 2013 and go to your Site Assets folder. Create a folder structure where a “ MasterPageScripts ” folder is inside a “ Scripts ” folder, which is inside the “ Site Assets ” folder: Site Assets > Scripts > MasterPageScripts Download jQuery-1.12.3.min here and save it into the MasterPageScripts folder.