Search This Blog

Tuesday, December 3, 2019

SharePoint Multiple file upload - using angularJs and callback method


<input type="file" ng-model="fileName" multiple onchange="angular.element(this).scope().upload(this)" id="file" name="file" />



     function insertPJFiles(PJlistItemId, message, redirectUrl) {

            if ($scope.appProperties.PJFiles.length > 0) {
                var oList = web.get_lists().getByTitle(Config.PJDocuments);
                PJService.getDocLibByFolderName(PJlistItemId).then(function (response) {                 
                    if (response.data.d.results.length > 0) {
                        //alread exit folder     
                        uploadFile(PJlistItemId, $scope.appProperties.PJFiles);                      
                    }
                    else {
                        // Folder doesn't exist at all. so create folder here
                        var oListItem = oList.get_rootFolder().get_folders().add(PJlistItemId); //foldername used by PJApproval listItemID
                        ctx.load(oListItem);
                        ctx.executeQueryAsync(function () {

                            uploadFile(PJlistItemId, $scope.appProperties.PJFiles);
                          
                          
                        }, function (sender, args) {
                            console.log("something went wrong");
                            console.log('Err: ' + args.get_message());
                        });
                    }
                });

            }
}
----------------------------------------------   
    //add file to repeat
        $scope.upload = function (obj) {
            if (obj.files.length > 0 && ($scope.appProperties.FileTemplateType!="" && $scope.appProperties.FileTemplateType!=null)) {
                $scope.loaded = true;
                var fileExit = false;
                for (var i = 0; i < obj.files.length; i++) {
                    var file = obj.files[i];
                    var reader = new FileReader();
                    //Getting the File name              
                    reader.filename = file.name;
                    //Getting the extention of the file
                    var ext = file.name.match(/\.([^\.]+)$/)[1];
                    reader.onloadend = function (e) {
                        //Validating the uploaded file Format
                        switch (ext) {
                            case 'pdf':
                            case 'docx':
                            case 'doc':
                            case 'excel':
                            case 'xlsm':
                            case 'xls':
                            case 'xlsx':
                                if ($scope.appProperties.PJFileProperties.length == 0) {
                                    $scope.appProperties.PJFiles.push(file); //insert purpouse- suing this properties
                                    $scope.appProperties.PJFileProperties.push({ fileName: file.name, template: $scope.appProperties.FileTemplateType, url: "#" }); //in dispay in UI html page using this properties
                                    $scope.isSelectedFile = false;//for validation
                                
                                    $scope.$apply(); // force digest cycle
                                }
                                else {
                                    angular.forEach($scope.appProperties.PJFileProperties, function (value, key) {
                                        if (value.fileName.indexOf(file.name) !== -1) {
                                            fileExit = true;
                                            alert("File already added")
                                        }
                                    });
                                    if (!fileExit) {
                                        $scope.appProperties.PJFiles.push(file); //insert purpouse- suing this properties
                                        $scope.appProperties.PJFileProperties.push({ fileName: file.name, template: $scope.appProperties.FileTemplateType, url: "#" }); //in dispay in UI html page using this properties
                                        $scope.isSelectedFile = false;//for validation                                    
                                        $scope.$apply(); // force digest cycle
                                    }
                                }
                                break;
                            default:
                                alert('Invalid format');
                        }//switch
                    };
                    reader.readAsDataURL(file);
                    $scope.loaded = false; //spinner stop  
                }
                $scope.$apply();//event callback.
            }
            else {
                alert('Please Select template !!!');
            }
        };

----------------------------------------------------------------------
        //Below code is for Upload the file.
        // You can upload files up to 2 GB with the REST API.
        function uploadFile(PJListItemID,fileInput) {
            var deferred = $.Deferred();

            // Define the folder path for this example.
             //Ex: '/sites/<Site>/<SubSite>/<LibraryName>';

            // Get test values from the file input and text input page controls.
           // var fileInput = jQuery('#FileUpload');

            // Get the server URL.
            var serverUrl = _spPageContextInfo.webAbsoluteUrl;

            // Below Code call all files in a loop, Initiate method calls using jQuery promises.
            // Get the local file as an array buffer.
            (function Tasks(i, callback) {
                if (i < fileInput.length) {
                    var success = ProcessFiles(i);
                    success.done(function () { Tasks((i + 1), callback); });
                }
                else {
                    callback();
                }
            })(0, function () { 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(arrayBuffer, ind);
                    addFile.done(function (file, status, xhr) {

                        // Get the list item that corresponds to the uploaded file.
                        var getItem = getListItem(file.d.ListItemAllFields.__metadata.uri);
                        getItem.done(function (listItem, status, xhr) {

                            // 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");
                                deferred.resolve();
                            });
                            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(fileInput[ind]);
                return deferred.promise();
            }
            // Below code Add the file to the file collection in the Shared Documents folder.
            function addFileToFolder(arrayBuffer, ind) {
                // Get the file name from the file input control on the page.
                var fileName = fileInput[ind].name;
                // Construct the endpoint.        
                var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/PJDocuments/" + PJListItemID;
                var fileCollectionEndpoint = serverUrl + "/_api/Web/GetFolderByServerRelativeUrl(@target)/Files/add(overwrite=true, url='" + fileName + "')?@target='" + targetUrl + "'&$expand=ListItemAllFields,ListItemAllFields/PJListItemID,ListItemAllFields/Template";

                // 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(itemMetadata, ind) {
                //Adding ID with file name here
                var newName = fileInput[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}','PJListItemID':'{3}'}}",
          itemMetadata.type, newName, newName, PJListItemID);

                // 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"
                    }
                });
            }
            return deferred.promise();
        }

        //Below code for Display error messages.
        function onError(error) {
            alert(error.responseText);
        }

No comments:

Post a Comment