Pages

Friday, August 25, 2017

Add an Attachment to a list item with PnP JS Core library and Dropzone.js

Introduction

I was using ng-dropzone which is a AngularJS directive for dropzone.js and PnP JavaScript Core Library in order to add an attachment for list item.

I was following this url in order setup dropzone.js in my SharePoint hosted add-in.

In order to add an attachment to SharePoint list item please do the below changes.

  1. Replace $scope.dzCallbacks as below
  2.   
          $scope.dzCallbacks = {
                'addedfile': function (file) {
                    console.log(file);
                    $scope.dropZoneFiles.push(file);
                },
                'success': function (file, xhr) {
                    console.log(file, xhr);
                },
            };
  3. Add below function to insert item and add attachment

Since my solution is a SharePoint hosted add-in I’m using crossDomain call and you have to replace your addinWeb and hostWeb url and also your have to change the list name. My list name is “abc”

  
     $scope.saveItem = function () {
          
            $pnp.sp.crossDomainWeb(addinWeb, hostWeb).lists.getByTitle("abc").items.add({
                Title: "Title",

            }).then((result) => {
              
                $scope.dropZoneFiles.forEach(function (file) {
                    var toUpload = file; 
                    
                    var r = new FileReader();

                    r.onloadend = function (e) {
                        var data = e.target.result;


                        item.attachmentFiles.add(toUpload.name, data).then(function () {
                            alert()
                        });
                    }

                    r.readAsArrayBuffer(toUpload);
                    
                    console.log(result);
                });
            }

Conclusion

The item will be created and the attachment will be uploaded.

No comments:

Post a Comment