<script type="text/javascript">


function uploadFileAsAttachment(itemId, fileInput) {

  var file = fileInput.files[0];

  

  if (file) {

    var context = SP.ClientContext.get_current();

    var web = context.get_web();

    var list = web.get_lists().getByTitle("Your List Name");

    var listItem = list.getItemById(itemId);

    

    // Read the file data

    var reader = new FileReader();

    

    reader.onloadend = function (evt) {

      if (evt.target.readyState == FileReader.DONE) {

        // Create a new file creation information object

        var attachmentInfo = new SP.AttachmentCreationInformation();

        attachmentInfo.set_contentType(file.type);

        attachmentInfo.set_fileName(file.name);

        attachmentInfo.set_attachmentContent(new SP.Base64EncodedByteArray());

        

        // Convert the file data to byte array

        var byteArray = new Uint8Array(evt.target.result);

        

        for (var i = 0; i < byteArray.byteLength; i++) {

          attachmentInfo.get_attachmentContent().append(byteArray[i]);

        }

        

        // Add the attachment to the list item

        listItem.get_attachmentFiles().add(attachmentInfo);

        

        // Update the list item

        listItem.update();

        

        // Execute the update request

        context.executeQueryAsync(

          function () {

            // Attachment uploaded successfully

            console.log("Attachment uploaded successfully");

          },

          function (sender, args) {

            // Error occurred while uploading attachment

            console.log("Error uploading attachment: " + args.get_message());

          }

        );

      }

    };

    

    // Read the file as an ArrayBuffer

    reader.readAsArrayBuffer(file);

  }

}


</script>


<!-- HTML Markup -->

<input type="file" id="fileInput" />

<button onclick="uploadFileAsAttachment(1, fileInput)">Upload</button>


Comments

Popular posts from this blog

Bulk update and delete using SPservice in SharePoint

Javascript function to populate from query string