Search This Blog

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();
    }
};



No comments:

Post a Comment