1

I have an infopath form that uses a custom (html) form submit button. The click event of the submit button adds the item to the list using REST API. The only issue is that when the user uploads an attachment to the list item , submitting the form does not add the attachment to the list item.

Can anyone suggest a way to achieve this.

1 Answer 1

3

We cannot upload attachments for new item in a single REST call. Because uploading attachment needs item ID for the new item it does not exist until the item is created.

First, create the item based on the information entered in the form, and get the latest item ID (new created item ID) from the list using code. Then, add attachments to item.

Use the REST API below to add attachments to the item

/_api/lists/GetByTitle('" + listName + "')/items(" + itemId + ")/AttachmentFiles/add(FileName='" + file.name + "')

Here is a demo about how to add attachments to an item using REST API:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.1a/jquery.SPServices-0.7.1a.min.js"></script>
    var context;
    var web;
    var Url;
    var listItemEntity;
    // change list name to yours
    var listName="<list>"
    //get the new created item id from the list
    var itemId = $().SPServices.SPGetLastItemId({   
        listName: listName
        });

    $(document).ready(function () {
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', FunctionReady);
        ItemSubmit();
    });
    function FunctionReady() {
        context = new SP.ClientContext.get_current();
        web = context.get_web();
        context.load(web);
        context.executeQueryAsync(onRequestSuccess, onRequestFailure);
    }
    function onRequestSuccess() {
        Url = web.get_url();
        GetListItemEntity(Url);
    }
    function onRequestFailure(sender, args) {
        alert("Error Occured:" + args.get_message());
    }
    //Used to get the List Item Entity Type
    function GetListItemEntity(webUrl) {
        var queryUrl = webUrl + "/_api/lists/getbytitle('"+listName+"')?$select=ListItemEntityTypeFullName";
        $.ajax({
            url: queryUrl,
            method: "GET",
            headers: { "Accept": "application/json;odata=verbose" },
            success: onEntitySuccess,
            error: onEntityFailure
        });
    }
    function onEntitySuccess(data) {
        listItemEntity = data.d.ListItemEntityTypeFullName;
    }
    function onEntityFailure(err) {
        alert(err.statusText);
    }
    function ItemSubmit() {
        //Button click Event to upload files to List Item
        $("#btnSubmit").click(function () {
            //checking Whether document is uploaded or not - Validation
            if (document.getElementById("inputFile").files.length === 0) {
                alert("Select a file..and click on submit");
                return;
            }
            else {
                //Reading the Uploadef file values
                var parts = document.getElementById("inputFile").value.split("\\");
                var filename = parts[parts.length - 1];
                var file = document.getElementById("inputFile").files[0];                  
                //filename - File Name of the attachment
                //file - file data
                uploadFileSP(listName, itemId, filename, file);
            }
        });
    }
    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 queryUrl = Url + "/_api/lists/GetByTitle('" + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + file.name + "')";
              $.ajax({
                              url: queryUrl,
                              type: "POST",
                              processData: false,
                              contentType: "application/json;odata=verbose",
                              data: buffer,
                              headers: {
                                              "accept": "application/json;odata=verbose",
                                              "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                                              "content-length": buffer.byteLength
                              }, success: onAttachmentSucess,
                              error: onAttachmentFailure
              });
            },
            function (err) {
                            deferred.reject(err);
            });
        return deferred.promise();
    }

    function onAttachmentSucess() {
        console.log('Attachement Added Successfully');
        //refresh the page
        window.location.reload(true);
    }

    function onAttachmentFailure(error) {
        console.log("Failure:" + error.status + "," + error.statusText);
    }

</script>


<table>
<tr>
  <td style="width:170px">
   <b>Attachments:    </b>
  </td>
  <td valign="top" class="ms-formbody" id="attachmentsOnClient">
   <input type="file" id="inputFile" />
  </td>
  <td>
   <input type="button" id="btnSubmit" value="Attach" />
  </td> 
 </tr>
</table>

For more information about how to add attachments to a list item using script, check the following thread:

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/7c165276-36e5-47eb-a435-d29383330efc/add-attachment-while-inserting-a-item-with-csom-javascript?forum=sharepointdevelopment

SharePoint 2013 REST API create list item with attachments javascript

2
  • Does this work on mobile devices as well? I can upload files from my computer but not from mobile devices.
    – Paul Vu
    Commented May 15, 2020 at 13:58
  • Does this code handle multi file upload ? Commented Jul 18, 2021 at 8:48

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.