1

I'm using HTML to create a custom list with bootstrap and then JSOM to manipulate and display the list on a SP custom list.

I am looking to add attachments and I can't figure it out.

Can anyone help?

The HTML code is self explanatory so I won't include it.

Here is my JS Code:

<script>
var siteUrl = 'url goes HERE';  //use site URL where list is being hosted (NOT LIST URL)
function InsertintGetList() {  
    var spendPlanType = document.getElementById('spendPlanType').value;  
    var monthS = document.getElementById('month').value;  
    var dSS = document.getElementById('dSS').value;  
    var directorate = document.getElementById('directorate').value;  
    var description = document.getElementById('description').value;  
    var projectedA = document.getElementById('projectedA').value;  
    var actualA = document.getElementById('actualA').value;  
    var justification = document.getElementById('justification').value;  
    var startD = document.getElementById('startD').value;
    var endD = document.getElementById('endD').value;
    var recompete = document.getElementById('recompete').value;
    var documentNumber = document.getElementById('documentNumber').value;
    var contractNumber = document.getElementById('contractNumber').value;
    var pec = document.getElementById('pec').value;
    var rccc = document.getElementById('rccc').value; 
    var subObjectClass = document.getElementById('subObjectClass').value; 
    var eEIC = document.getElementById('eEIC').value; 
    var espCode = document.getElementById('espCode').value;
    var recuring = document.getElementById('recuring').value;
    var techPm = document.getElementById('techPm').value; 
    var dateObligated = document.getElementById('dateObligated').value; 
    var notes = document.getElementById('notes').value; 
    var clientContext = new SP.ClientContext(siteUrl);  
    var GetList = clientContext.get_web().get_lists().getByTitle('SpendPlan');  //name of list on SharePoint
    var itemCreateInfo = new SP.ListItemCreationInformation();  
        this.GetListItem = GetList.addItem(itemCreateInfo);  
        GetListItem.set_item('Spend_x0020_Plan', spendPlanType); 
        GetListItem.set_item('Month', monthS);  
        GetListItem.set_item('d_x002f_SS', dSS);  
        GetListItem.set_item('Directorates', directorate);  
        GetListItem.set_item('Description', description);
        GetListItem.set_item('Projected_x0020_Amount', projectedA);  
        GetListItem.set_item('Actual_x0020_Amount', actualA);  
        GetListItem.set_item('Justification_x002f_Mission', justification);  
        GetListItem.set_item('PoP_x0020_Start_x0020_Date', startD);  
        GetListItem.set_item('PoP_x0020_End_x0020_Date', endD);
        GetListItem.set_item('Recompete_x0020_Date', recompete);
        GetListItem.set_item('Document_x0020_Number', documentNumber);
        GetListItem.set_item('Contract_x0020_Number', contractNumber);
        GetListItem.set_item('PEC', pec );
        GetListItem.set_item('RCCC', rccc);
        GetListItem.set_item('Sub_x0020_object_x0020_Class', subObjectClass);
        GetListItem.set_item('EEIC', eEIC);
        GetListItem.set_item('ESP_x0020_Code', espCode);
        GetListItem.set_item('One_x002d_time_x0020_or_x0020_Re', recuring);
        GetListItem.set_item('Tech_x002f_PM_x0020_POC', techPm);
        GetListItem.set_item('Date_x0020_Obligated', dateObligated);
        GetListItem.set_item('Notes', notes);
        GetListItem.update();  
        clientContext.load(GetListItem);  
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));  
    }  
function onQuerySucceeded() {  
    alert('Record Inserted'); 
    document.getElementById("spendPlanType").value = "";   
    document.getElementById("month").value = "";  
    document.getElementById("dSS").value = "";  
    document.getElementById("directorate").value = "";  
    document.getElementById("description").value = "";  
    document.getElementById("projectedA").value = "";  
    document.getElementById("actualA").value = "";  
    document.getElementById("justification").value = "";  
    document.getElementById('startD').value = "";
    document.getElementById('endD').value = "";
    document.getElementById("recompete").value = "";  
    document.getElementById("documentNumber").value = "";  
    document.getElementById('contractNumber').value = "";
    document.getElementById('pec').value = "";
    document.getElementById("rccc").value = "";  
    document.getElementById("subObjectClass").value = "";  
    document.getElementById('eEIC').value = "";
    document.getElementById('espCode').value = "";
    document.getElementById("recuring").value = "";   
    document.getElementById("techPm").value = "";  
    document.getElementById("dateObligated").value = "";  
    document.getElementById("notes").value = ""; 
}  
function onQueryFailed(sender, args) {  
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
   }  
   
</script>
1

1 Answer 1

0

It is possible to upload attachments to SharePoint list item using JSOM.

Here's the sample code taken from 1st reference link (given below):

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<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];
        //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('NewList');
        var attachmentFolder = oWeb.getFolderByServerRelativeUrl('/sites/dev/Lists/NewList/Attachments/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" />

Where NewList is name of the list (name in URL & not display name) and 1 is list item ID at this line:

var attachmentFolder = oWeb.getFolderByServerRelativeUrl('/sites/dev/Lists/NewList/Attachments/1');

Refer below articles for detailed information & code snippets:

  1. Upload list item attachment using JSOM
  2. Upload list item attachment using JSOM
  3. Upload File To List Item In Office 365 As An Attachment Using JavaScript Object Model
2
  • The code I have above creates a new item in a list using JSOM. Do I have to add the id manually so that the attachment can be uploaded to the correct item? Or will it be done automatically with each new list I create?
    – Robbie
    Aug 10, 2022 at 17:25
  • You can get the item ID of newly created list item in onQuerySucceeded function. Inside this function, you can call the function to upload the attachments. Aug 10, 2022 at 18:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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