none
Sharepoint Multiple Ajax calls - Need an example for Uploading attachments to list item thru REST API RRS feed

  • Question

  • Hi Team,

    Could you please any of you help me on getting the below task done.

    I am trying to upload the attachments to various items on the same list. As i am trying client side scripting + rest api method am able to add the attachment. 

    But i have multiple files to upload and need an example to achieve this.  

    Code :

    <input id="inputFile" type="file" >
    <input id="uploadDocumentButton" type="Button" value="Upload Document">

    <script src="../Shared Documents/jquery-1.11.0.min.js" type="text/javascript"></script>

    <script type="text/javascript">

    $("#uploadDocumentButton").click(function () {

        if (document.getElementById("inputFile").files.length === 0) {

            alert("Select a file!");
            return;

        }

        var parts = document.getElementById("inputFile").value.split("\\");
        var filename = parts[parts.length - 1];
        var file = document.getElementById("inputFile").files[0];
        uploadFile("ListA", "10", filename, file);                                               

    });

    function uploadFile(listName, listId, fileName, file){

                    uploadFileSP(listName, listId, fileName, file)
                                    .then(                                   
                                        function (files) {                                            
                                            alert("Uploaded successfully");                                         
                                        },                                         
                                        function (sender, args) {                                           
                                            alert(args.get_message());                                  
                                        }                                          
                                    );                             

    }

    function getFileBuffer(file){

                    var deferred = $.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();

    }

    function uploadFileSP(listName, id, fileName, file){

                    var deferred = $.Deferred();
                    getFileBuffer(file).then(
                                    function(buffer){

                                                    var bytes = new Uint8Array(buffer);
                                                    var content = new SP.Base64EncodedByteArray();
                                                    var binary = '';
                                                    for(var b=0; b<bytes.length; b++){
                                                                    binary += String.fromCharCode(bytes[b]);                                                    

                                                    }

                                                    var scriptbase = _spPageContextInfo.webServerRelativeUrl+ "/_layouts/15/";

                                                    $.getScript(scriptbase + "SP.RequestExecutor.js", function(){

                                                                    var createitem = new SP.RequestExecutor("https://site.sharepoint.com/sites/jason/test/");

                                                        createitem.executeAsync({

                                                            url: "https://site.sharepoint.com/sites/jason/test/_api/web/lists/GetByTitle('"+listName+"')/items("+id+")/AttachmentFiles/add(FileName='" + file.name + "')",
                                                            method: "POST",
                                                            binaryStringRequestBody: true,
                                                            body: binary,
                                                            success: fsucc,
                                                            error: ferr,
                                                            state: "Update"

                                                        });
                                                  

                                                        function fsucc(data) {
                                                            alert('success');
                                                        }
                                                  

                                                        function ferr(data) {
                                                            alert('error\n\n' + data.statusText + "\n\n" + data.responseText);
                                                        }

                                                    });           

                                    },

                                    function(err){
                                                    deferred.reject(err);
                                    }

                    );

                    return deferred.promise();

    }

    </script>

    Dhana


    Dhana-Chennai-India



    Friday, April 14, 2017 8:33 AM

All replies

  • Hi,

    I did a little update based on your code, you could check the code for your reference.

    (add a content editor web part to your page and add below code to it)

    <script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#uploadDocumentButton").click(function () {
                    if (document.getElementById("inputFile").files.length === 0) {
                        alert("Select a file!");
                        return;
                    }
    
                    var parts = document.getElementById("inputFile").value.split("\\");
                    var filename = parts[parts.length - 1];
                    var file = document.getElementById("inputFile").files[0];
                    uploadFile("ListA", "1", filename, file);
    
                }
                )
            })
    
            function uploadFile(listName, listId, fileName, file) {
    
                uploadFileSP(listName, listId, fileName, file)
                                .then(
                                    function (files) {
                                        alert("Uploaded successfully");
                                    },
                                    function (sender, args) {
                                        alert(args.get_message());
                                    }
                                );
    
            }
    
            function getFileBuffer(file) {
    
                var deferred = $.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();
    
            }
    
            function uploadFileSP(listName, id, fileName, file) {
                var deferred = $.Deferred();
                getFileBuffer(file).then(
                                function (buffer) {
                                    //var bytes = new Uint8Array(buffer);
                                    //var content = new SP.Base64EncodedByteArray();
                                    //var binary = '';
                                    //for (var b = 0; b < bytes.length; b++) {
                                    //    binary += String.fromCharCode(bytes[b]);
    
                                    //}
    
                                    $.ajax({
                                        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + file.name + "')",
                                        type: 'POST',
                                        data: buffer,
                                        processData: false,
                                        headers: {
                                            "X-RequestDigest": $('#__REQUESTDIGEST').val(),
                                            "content-length": buffer.byteLength
                                        },
                                        success: fsucc,
                                        error: ferr,
                                    });
    
                                    //var scriptbase = _sppagecontextinfo.webserverrelativeurl + "/_layouts/15/";
                                    //$.getscript(scriptbase + "sp.requestexecutor.js", function () {
                                    //    var createitem = new sp.requestexecutor("https://site.sharepoint.com/sites/jason/test/");
                                    //    createitem.executeasync({
                                    //        url: _sppagecontextinfo.webabsoluteurl +"/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")/attachmentfiles/add(filename='" + file.name + "')",
                                    //        method: "post",
                                    //        binarystringrequestbody: true,
                                    //        data: buffer,
                                    //        success: fsucc,
                                    //        error: ferr,
                                    //        state: "update"
    
                                    //    });
    
                                    function fsucc(data) {
                                        alert('success');
                                    }
    
                                    function ferr(data) {
                                        alert('error\n\n' + data.statusText + "\n\n" + data.responseText);
                                    }
    
                                },
                                 function (err) {
                                     deferred.reject(err);
                                 }
                                );
                return deferred.promise();
            }
    
    
    
            //);
            //return deferred.promise();
    
            //}
        </script>
        <input id="inputFile" type="file">
        <input id="uploadDocumentButton" type="Button" value="Upload Document">

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Monday, April 17, 2017 2:28 AM
  • Hi,

    I am checking to see how things are going there on this issue. Please let us know if you would like further assistance.

    You can mark the helpful post as answer to help other community members find the helpful information quickly.

    You can also share your own solution here and mark it as answer, so it may help others who has similar requirement.

    Best Regards,

    Lee


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Thursday, May 4, 2017 8:28 AM