简体   繁体   中英

Sharepoint - Add list item with attachment file, using javascript

I add some values and attachment to sharepoint list. I'm doing this with two different requests. One request for values, another for attachment. But while doing this, I need to run the updateDealerListItemNew2 function, which I added the values to, after adding the attachments. In the current state of my code updateDealerListItemNew2 doesn't work after all. It works before getFile.done and that's a problem for me. If I was adding a single attachment I could write my updateDealerListItemNew2 function in getFile.done but I am adding multiple attachments and I don't want to call this function inside the for. If I do that, it will update the values 2 times. I need to go back and run the updateDealerListItemNew2 after the getFile.done parts work and everything is finished in 'for' loop.

The reason I want this is to act on the triggered flow when one of the values I added changes. But right now my flow is working in the request where I added the attachments.

Briefly ; I need to call the updateDealerListItemNew2 function after every action in the UploadFiles function is finished.

Html-

<form>
   <input type="text" id="ad" name="filter"/>
   <input type="text" id="soyad" name="filter"/>
   <input type="file" id="file" name="filter" multiple/>
   <button type="button" id="SendApproval" onclick="BtnSendApproval()"  >Send</button>
</form>

Javascript-

function BtnSendApproval() {
    var ad = $("#ad").val();
    var soyad = $("#soyad").val();

    var itemType = "SP.Data.UsersListItem";
    var cItem = {
        __metadata: {
            type: itemType,
        }
    };

    cItem = $.extend({}, cItem, {
        Title: ad,
        Soyad: soyad
    });

    UploadFiles(1, 'Users', cItem);


}

function UploadFiles(dealerId, listName, cItem) {
    var fileInput = jQuery('#file');
    var fileCount = fileInput[0].files.length;
    var filesUploaded = 0;
    if (fileCount > 0) {
        for (var i = 0; i < fileCount; i++) {
            if (fileInput[0].files[i].size > 0) {
                // Initiate method calls using jQuery promises.
                // Get the local file as an array buffer.
                var getFile = getFileBuffer(i);
                getFile.done(function (arrayBuffer, i) {
                    // Add the file to the SharePoint ListItem.
                    var addFile = addFileToListItem(arrayBuffer, i);
                    addFile.done(function (file, status, xhr) {
                        console.log(i + "added");
                    });
                    addFile.fail(onFileUploadError);
                });
                getFile.fail(onFileUploadError);
            }
        }

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

        function addFileToListItem(arrayBuffer, i) {
            var index = i;
            // Get the file name from the file input control on the page.
            var fileName = fileInput[0].files[index].name;
            listName = "Users";
            // Send the request and return the response.
            // This call returns the SharePoint file.
            return jQuery.ajax({
                // url: fileCollectionEndpoint,
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + 1 + ")/AttachmentFiles/add(FileName='" + fileName + "')",
                type: "POST",
                async: false,
                data: arrayBuffer,
                processData: false,
                headers: {
                    "Accept": "application/json; odata=verbose",
                    "content-type": "application/json; odata=verbose",
                    "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
                }
            });
        }
    }
    updateDealerListItemNew2(dealerId, listName, cItem, function () {
        console.log('Record updated successfully..');
    });
}

function onFileUploadError(error) {
    console.log("FileUpload ERROR: " + error.responseText);
}


function updateDealerListItemNew2(itemId, listName, cItem, success) {

    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl +
            "/_api/web/lists/getbytitle('" +
            listName +
            "')/getitembyid(" +
            itemId +
            ')',
        type: 'POST',
        contentType: 'application/json;odata=verbose',
        data: JSON.stringify(cItem),
        headers: {
            Accept: 'application/json;odata=verbose',
            'Content-Type': 'application/json;odata=verbose',
            'X-RequestDigest': $('#__REQUESTDIGEST').val(),
            'IF-MATCH': '*',
            'X-HTTP-Method': 'MERGE',
        },
        success: function (data) {
            //  $("#dealerForm").modal("hide");
            console.log('BAŞARILI Record updated successfully2..');
            success(data);

        },
    });
}

Please refer to following code to add attachment to list item

<script type="text/javascript">
        var fileInput;  
        $(document).ready(function()   
        {  
            fileInput = $("#getFile");  
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);  
        });  
  
        function registerClick()   
        {  
            //Register File Upload Click Event  
            $("#addFileButton").click(readFile);  
        }  
        var arrayBuffer;  
  
        function readFile()   
        {  
            //Get File Input Control and read th file name  
            var element = document.getElementById("getFile");  
            var file = element.files[0];  
            var parts = element.value.split("\\");  
            var fileName = parts[parts.length - 1];  
            console.log(parts);
            console.log(fileName);
            //Read File contents using file reader  
            var reader = new FileReader();  
            reader.onload = function(e) {  
                uploadFile(e.target.result, fileName);  
            }  
            reader.onerror = function(e)   
            {  
                alert(e.target.error);  
            }  
            reader.readAsArrayBuffer(file);  
        }  
        var attachmentFiles, clientContext, createInfo;  
  
        function uploadFile(arrayBuffer, fileName)   
        {  
            //Get Client Context and Web object.  
            clientContext = new SP.ClientContext();  
            var oWeb = clientContext.get_web();  
  
            //Get list and Attachment folder where the attachment of a particular list item is stored.  
            var oList = oWeb.get_lists().getByTitle('TestList01');  
            var attachmentFolder = oWeb.getFolderByServerRelativeUrl('/sites/xiexin/Lists/TestList05/xie/1');  
  
            //Convert the file contents into base64 data  
            var bytes = new Uint8Array(arrayBuffer);  
            var i, length, out = '';  
            for (i = 0, length = bytes.length; i < length; i += 1) {  
                out += String.fromCharCode(bytes[i]);  
            }  
            var base64 = btoa(out);  
            //Create FileCreationInformation object using the read file data  
            createInfo = new SP.FileCreationInformation();  
            createInfo.set_content(base64);  
            createInfo.set_url(fileName);  
  
            //Add the file to the list item  
            attachmentFiles = attachmentFolder.get_files().add(createInfo);  
  
            //Load client context and execute the batch  
            clientContext.load(oList);  
            clientContext.load(attachmentFiles);  
            clientContext.executeQueryAsync(QuerySuccess, QueryFailure);  
        }  
  
        function QuerySuccess()   
        {  
            console.log("Attachment added successfuly ");  
        }  
  
        function QueryFailure(sender, args)   
        {  
            console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());  
        }  
</script>

    <input id="getFile" type="file" /><br />  
    <input id="addFileButton" type="button" value="Upload" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM