I'm using SP Online. I have the following code to update a list item. I added this code in a script editor inside EditForm.aspx. It works fine and I'm able to update several fields, but If user adds attachments using the default attachments button, I'm not able to save the attachments. How can I modify the script to include the attachments when calling item.update() method?

<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />

<script type="text/javascript"> 

function doFunction() {
    var testnum2 = $("input[Title='testnum2']").val();
    var context = new SP.ClientContext(_spPageContextInfo.webServerRelativeUrl);
    var list = context.get_web().get_lists().getById(_spPageContextInfo.pageListId);
    var getweb = context.get_web();
    var itemID = parseInt(GetUrlKeyValue('ID'));
    var item = list.getItemById(itemID);

    getweb.AllowUnsafeUpdates = false;
    context.load(item);
    item.set_item('testnum2',testnum2);

    item.update();
    context.executeQueryAsync(RetrievedListID, ExecutionFailed);

    //response handler

    function RetrievedListID(sender, args) {

    }

    //error handler - generic

    function ExecutionFailed(sender, args) {

    }
}

</script>
up vote 2 down vote accepted

You can create a custom File Upload control <input id="file_input" type="file"> (if you want to upload multiple files, use "jquery.multifile.js" plugin). Get files from the custom control and then upload files as attachments using REST API _api/web/lists/getbytitle('list title')/items(item id)/AttachmentFiles/add(FileName='file name')

Here is a demo about how to create a new item with multiple attachments. You can change the code for item edition to achieve your requirement:

<script type="text/javascript" src="/teams/MySCForApps/Style Library/JS/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/teams/MySCForApps/Style Library/JS/jquery-ui.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script type="text/javascript" src="/teams/MySCForApps/Style Library/JS/jquery.MultiFile.js"></script>
<link rel="Stylesheet" type="text/css" href="../CSS/App.css" />
<script language="javascript" type="text/jscript">
    $(function () {
        var fileCountCheck = 0;
        $("#btnSubmit").click(function () {
            var data = [];
            var fileArray = [];
            $("#attachFilesContainer input:file").each(function () {
                if ($(this)[0].files[0]) {                    
                    fileArray.push({ "Attachment": $(this)[0].files[0] });                    
                }
            });
            data.push({"FirstName": $("#txtFirstName").val().trim(), "LastName": $("#txtLastName").val().trim(), "Files": fileArray});            
            createItemWithAttachments("MyList", data).then(
                function(){
                    alert('Item created with Multiple attachments');
                },
                function(sender, args){
                    console.log('Error occured' + args.get_message());
                }
            )

        });

        var createItemWithAttachments = function(listName, listValues){         
            var fileCountCheck = 0;
            var fileNames;          
            var context = new SP.ClientContext.get_current();
            var dfd = $.Deferred();
            var targetList = context.get_web().get_lists().getByTitle(listName);
            context.load(targetList);
            var itemCreateInfo = new SP.ListItemCreationInformation();
            var listItem = targetList.addItem(itemCreateInfo);   
            listItem.set_item("FirstName", listValues[0].FirstName);
            listItem.set_item("LastName", listValues[0].LastName); 
            listItem.update();
            context.executeQueryAsync(
                function () {
                    var id = listItem.get_id();
                    if (listValues[0].Files.length != 0) {
                        if (fileCountCheck <= listValues[0].Files.length - 1) {
                            loopFileUpload(listName, id, listValues, fileCountCheck).then(
                                function () {
                                },
                                function (sender, args) {
                                    console.log("Error uploading");
                                    dfd.reject(sender, args);
                                }
                            );
                        }
                    }
                    else {
                        dfd.resolve(fileCountCheck);
                    }
                },   
                function(sender, args){
                    console.log('Error occured' + args.get_message());              
                }
            );
            return dfd.promise();           
        }

        function loopFileUpload(listName, id, listValues, fileCountCheck) {
            var dfd = $.Deferred();
            uploadFile(listName, id, listValues[0].Files[fileCountCheck].Attachment).then(
                function (data) {                      
                    var objcontext = new SP.ClientContext();
                    var targetList = objcontext.get_web().get_lists().getByTitle(listName);
                    var listItem = targetList.getItemById(id);
                    objcontext.load(listItem);
                    objcontext.executeQueryAsync(function () {
                        console.log("Reload List Item- Success");                                        
                        fileCountCheck++;
                        if (fileCountCheck <= listValues[0].Files.length - 1) {
                            loopFileUpload(listName, id, listValues, fileCountCheck);
                        } else {
                            console.log(fileCountCheck + ": Files uploaded");
                            alert('Item created with Multiple attachments');                            
                        }
                    },
                    function (sender, args) {
                        console.log("Reload List Item- Fail" + args.get_message());
                    });                  

                },
                function (sender, args) {
                    console.log("Not uploaded");
                    dfd.reject(sender, args);
                }
           );
           return dfd.promise();
        }

        function uploadFile(listName, id, file) {
            var deferred = $.Deferred();
            var fileName = file.name;
            getFileBuffer(file).then(
                function (buffer) {
                    var bytes = new Uint8Array(buffer);
                    var binary = '';
                    for (var b = 0; b < bytes.length; b++) {
                        binary += String.fromCharCode(bytes[b]);
                    }
                    var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
                    console.log(' File size:' + bytes.length);
                    $.getScript(scriptbase + "SP.RequestExecutor.js", function () {
                        var createitem = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);
                        createitem.executeAsync({
                            url: _spPageContextInfo.webServerRelativeUrl + "/_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) {
                            console.log(data + ' uploaded successfully');
                            deferred.resolve(data);
                        }
                        function ferr(data) {
                            console.log(fileName + "not uploaded error");
                            deferred.reject(data);
                        }
                    });

                },
                function (err) {
                    deferred.reject(err);
                }
            );
            return deferred.promise();
        }
        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();
        }
    }); 
</script>
<div class="fld">
    <div>
        <span>First Name</span>
        <span><input type="text" id="txtFirstName"></span>  
    </div>
    <div>
        <span>Last Name</span>
        <span><input type="text" id="txtLastName"></span>   
    </div>

    Attach any relevant files
    <div class="files" id="attachFilesContainer">
        <input id="infringementFiles" type="file" class="multi browsebtn" />
    </div>
</div>
<div class="fld">
    <input class="btn" id="btnSubmit" value="Submit" type="button" />
</div>

Refer to:

http://techfindings-prem.blogspot.com/2014/11/uploading-multiple-attachments-to-lists.html

https://www.c-sharpcorner.com/article/sharepoint-2013-uploading-multiple-attachments-to-the-new-item-on-list-using-j/

Another demo about how to upload a file as an attachment to a list item using CSOM in SharePoint Online:

https://www.c-sharpcorner.com/article/upload-file-to-listitem-in-office-365-as-an-attachment-using-javascript-object-m/

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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