Search This Blog

Showing posts with label SharePoint. Show all posts
Showing posts with label SharePoint. Show all posts

Saturday, January 23, 2021

SharePoint online - Multi attachments- inside list

 //change event

  <div class="form-group col-md-6">
  <span id="attach">
      <input id="uploadFileID" type="file" ng-file-model="files" multiple />                                               
      <span class="attach-Text" ng-repeat="file in files">
          <span>{{file.name}}</span><a title='Click to Remove' ng-click="removeFile(file, $index)"X </a>                                                    
      </span>
  </span>
</div>
--------------------------------Controller
$scope.name = 'UploadAttachements';
$scope.files = [];
$scope.removeFile = function (attachedFileindex) {
    var removedItem = $scope.files.indexOf(attachedFile);
    $scope.files.splice(removedItem1);
};       
$scope.saveAttachment = function (ListName,ListItemId) {
    if ($scope.files.length > 0) {
        var numberOfFiles = $scope.files.length;
        angular.forEach($scope.filesfunction (fileValueskey) {
            getFileBuffer(fileValues._file)
                .then(function (bufferVal) {
                    uploadFileSP(bufferValfileValues._file.nameListNameListItemId);
                    numberOfFiles--;
                    if (numberOfFiles == 0) {
                        console.log("attachment insert success");
                    }
                });
        });
    }
    else {
        alert('no files');
    }
}
function uploadFileSP(bufferValfileNamelistNameitemID) {         
      var urlValue = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(" + itemID + ")/AttachmentFiles/add(FileName='" + fileName + "')";

      $.ajax({
          url: urlValue,
          type: "POST",
          data: bufferVal,
          async: false,
          processData: false,
          headers: {
              "X-RequestDigest": $("#__REQUESTDIGEST").val(),
              "accept": "application/json;odata=verbose",
              "content-type": "application/json; odata=verbose"
          },
          success: fileSuccess,
          error: fileError
      });
      function fileSuccess(data) {
          console.log('File Added Successfully.');
      }
      function fileError(error) {
          console.log(error.statusText + "\n\n" + error.responseText);
      }
  }
  function getFileBuffer(file) {
      var deferred = $.Deferred();
      var reader = new FileReader();
      reader.onloadend = function (e) {
          deferred.resolve(e.target.result);
      }
      reader.onerror = function (e) {
          deferred.reject(e.target.error);
      }
      reader.readAsArrayBuffer(file);
      return deferred.promise();
  }
------------------------- add directive--------------------------
 app.directive('ngFileModel', ['$parse'function ($parse) {
      return {
          restrict: 'A',
          link: function (scopeelementattrs) {
              var model = $parse(attrs.ngFileModel);
              var isMultiple = attrs.multiple;
              var modelSetter = model.assign;
              element.bind('change'function () {
                  var values = [];
                  angular.forEach(element[0].filesfunction (item) {
                      var value = {
                          // File Name
                          name: item.name,
                          //File Size
                          size: item.size,
                          //File URL to view
                          url: URL.createObjectURL(item),
                          // File Input Value
                          _file: item
                      };
                      values.push(value);
                  });
                  scope.$apply(function () {
                      if (isMultiple) {
                          modelSetter(scopevalues);
                      } else {
                          modelSetter(scopevalues[0]);
                      }
                  });
              });
          }
      };
  }]);





Wednesday, August 19, 2020

Read Excel file using JavaScript with AngularJS- SharePoint online

 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/danialfarid-angular-file-upload/12.2.13/ng-file-upload.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.13.5/xlsx.full.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.13.5/jszip.js"></script>
<script type="text/javascript">
    var app = angular.module('MyApp', ['ngFileUpload'])
    app.controller('MyController'function ($scope$window) {
        $scope.SelectFile = function (file) {
            $scope.SelectedFile = file;
        };
        $scope.Upload = function () {
            var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx)$/;
            if (regex.test($scope.SelectedFile.name.toLowerCase())) {
                if (typeof (FileReader) != "undefined") {
                    var reader = new FileReader();
                    //For Browsers other than IE.
                    if (reader.readAsBinaryString) {
                        reader.onload = function (e) {
                            $scope.ProcessExcel(e.target.result);
                        };
                        reader.readAsBinaryString($scope.SelectedFile);
                    } else {
                        //For IE Browser.
                        reader.onload = function (e) {
                            var data = "";
                            var bytes = new Uint8Array(e.target.result);
                            for (var i = 0i < bytes.byteLengthi++) {
                                data += String.fromCharCode(bytes[i]);
                            }
                            $scope.ProcessExcel(data);
                        };
                        reader.readAsArrayBuffer($scope.SelectedFile);
                    }
                } else {
                    $window.alert("This browser does not support HTML5.");
                }
            } else {
                $window.alert("Please upload a valid Excel file.");
            }
        };
        $scope.CustomersSheet = [];
        $scope.ProcessExcel = function (data) {
            //Read the Excel File data.
            var workbook = XLSX.read(data, {
                type: 'binary'
            });
            //Display the data from Excel file in Table.
            $scope.$apply(function () {
                $scope.CustomersSheet = workbook.SheetNames;
            });
            $scope.onCategoryChange = function () {

                //  $window.alert("Selected Value: " + $scope.itemSelected);


                //Fetch the name of First Sheet.
                var firstSheet = $scope.itemSelected;//workbook.SheetNames[0];                      
                //Read all rows from First Sheet into an JSON array.
                var excelRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[firstSheet]);


                $scope.Customers = excelRows;
                $scope.IsVisible = true;

            };
        };

    });
</script>



<div ng-app="MyApp" ng-controller="MyController">
    <input type="file" ngf-select="SelectFile($file)"/>
    <input type="button" value="Upload" ng-click="Upload()"/>
    <hr/>
    <select ng-model="itemSelected" ng-change="onCategoryChange(itemSelected)">
        <option ng-repeat="x in CustomersSheet">{{x}}</option>
    </select>
    <table id="tblCustomers" cellpadding="0" cellspacing="0" ng-show="IsVisible" style="border: 1px; background-color: azure;">
    <tbody ng-repeat="m in Customers">
            <tr>
                <td>{{m.__EMPTY}}</td>
                <td>{{m.__EMPTY_1}}</td>
                <td>{{m.__EMPTY_2}}</td>
                <td>{{m.__EMPTY_3}}</td>
                <td>{{m.__EMPTY_4}}</td>
                <td>{{m.__EMPTY_5}}</td>
                <td>{{m.__EMPTY_6}}</td>                
            </tr>
        </tbody>
    </table>
</div>
<style>
    table {
      font-familyarialsans-serif;
      border-collapsecollapse;
      width100%;
    }
    
    tdth {
      border1px solid #dddddd;
      text-alignleft;
      padding8px;
    }
    
    tr:nth-child(even) {
      background-colorlightGray;
    }
    </style>

    

Friday, July 17, 2020

Upload Multiple Files with SharePoint - using JavaScript with AngularJs

controller.Js
-----------------------           
 // Define the folder path for this example.
            var serverRelativeUrlToFolder = '/sites/testsite/testDocuments/1';  
 //Ex: '/sites/<LibraryName>/<folderName>';
//$scope.files- multiplefile -array
            $scope.loaded = true;
            FileUtility.helpers.UploadFile($scope.files
serverRelativeUrlToFolderwebAbsoluteUrl).done(function () {
                $scope.loaded = false;

            });

fileupload.js - Add separate file - and call into html

var FileUtility = FileUtility || {};
FileUtility.helpers = {
    testfunc: function (restUrltoListccListsubjectmailContent) {

    },
    //Below code is for Upload the file.
    // You can upload files up to 2 GB with the REST API.
    UploadFile: function (files,serverRelativeUrlToFolder,webAbsoluteUrl) {
        var deferred = $.Deferred();
        // Below Code call all files in a loop, Initiate method calls using jQuery promises.
        // Get the local file as an array buffer.
        (function Tasks(icallback) {
            if (i < files.length) {
                var success = ProcessFiles(i);
                success.done(function () {
                    Tasks((i + 1), callback);                   
                });
            }
            else {
                callback();
            }
        })(0function () { deferred.resolve(); });

        //Below function call all the functions (GetFileBuffer,UploadFile,GettheLibraryItem,UpdatingTheItemColumns)
        function ProcessFiles(ind) {
            var deferred = $.Deferred();
            var getFile = getFileBuffer(ind);
            getFile.done(function (arrayBuffer) {
                // Add the file to the SharePoint folder.
                var addFile = addFileToFolder(arrayBufferind);
                addFile.done(function (filestatusxhr) {
                    // Get the list item that corresponds to the uploaded file.
                    var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
                    getItem.done(function (listItemstatusxhr) {
                        deferred.resolve();
                        // Change the display name and title of the list item.
                        // var changeItem = updateListItem(listItem.d.__metadata,ind);
                        //changeItem.done(function (data, status, xhr) {      
                        //alert("File "+ind+" uploaded");
                        // 
                        // });
                        // changeItem.fail(onError);
                    });
                    getItem.fail(onError);
                });
                addFile.fail(onError);
            });
            getFile.fail(onError);
            return deferred.promise();
        }
        // Below code Get the local file as an array buffer.
        function getFileBuffer(ind) {
            var deferred = jQuery.Deferred();
            var reader = new FileReader();
            reader.onloadend = function (e) {
                deferred.resolve(e.target.result);
            }
            reader.onerror = function (e) {
                deferred.reject(e.target.error);
            }
            reader.readAsArrayBuffer(files[ind]);
            return deferred.promise();
        }
        // Below code Add the file to the file collection in the Shared Documents folder.
        function addFileToFolder(arrayBufferind) {
            // Get the file name from the file input control on the page.
            var fileName = files[ind].name;
            // Construct the endpoint.
            var fileCollectionEndpoint = String.format(
                "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
                "/add(overwrite=true, url='{2}')",
                webAbsoluteUrlserverRelativeUrlToFolderfileName);

            // Send the request and return the response.
            // This call returns the SharePoint file.
            return jQuery.ajax({
                url: fileCollectionEndpoint,
                type: "POST",
                data: arrayBuffer,
                processData: false,
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                    "content-type": "application/json;odata=verbose"
                    //"content-length": arrayBuffer.byteLength
                }
            });
        }

        // Below code Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
        function getListItem(fileListItemUri) {
            // Send the request and return the response.
            return jQuery.ajax({
                url: fileListItemUri,
                type: "GET",
                headers: { "accept": "application/json;odata=verbose" }
            });
        }
        // Below code Update the display name and title of the list item.
        function updateListItem(itemMetadataind) {           
            var newName = files[ind].name;
            // Define the list item changes. Use the FileLeafRef property to change the display name. 
            // For simplicity, also use the name as the title. 
            // The example gets the list item type from the item's metadata, but you can also get it from the
            // ListItemEntityTypeFullName property of the list.
            var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
                itemMetadata.typenewNamenewName);

            // Send the request and return the promise.
            // This call does not return response content from the server.
            return jQuery.ajax({
                url: itemMetadata.uri,
                type: "POST",
                data: body,
                headers: {
                    "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                    "content-type": "application/json;odata=verbose",
                    //"content-length": body.length,
                    "IF-MATCH": itemMetadata.etag,
                    "X-HTTP-Method": "MERGE"
                }
            });
        }       
        //Below code for Display error messages. 
        function onError(error) {           
            alert(error.responseText);
            return false;
        }
        return deferred.promise();
    }
};