Search This Blog

Tuesday, November 7, 2017

Save List-item with Attachment- AngularJs/Sharepoint 2013

<input id="fileinput" type="file">
<input ng-click="saveAttachments($event)">
------------------------------------------------- 
 var maxFileSize = 5000000; //Set maximum file size value into a variable. 5 MB in bytes
    var fileName = []; // To keep track of uploaded file names
    var fileData = []; // Create an array to hold all the files
    var fileCount = 0; // To keep track on number of files uploaded into an array
    $scope.saveAttachments = function ($event) {
        //if (document.getElementById("fileinput").files.length === 0) {
        //    alert("Select a file!");
        //    return;
        //}
     
        //Getting the Target file
        var files = document.getElementById("fileinput").files;
        var file = files[0];
        if (files && file) {
            //Creating FileReader obj to read the uploaded file
            var reader = new FileReader();

            //Getting the File name
            fileName[fileCount] = file.name;
            reader.filename = file.name;

            //Getting the extention of the file
            var ext = file.name.match(/\.([^\.]+)$/)[1];

            //Getting the file size
            var fileSize = file.size;

            if (fileSize > maxFileSize)
                ext = 'sizeExceed';
            //var fileID = $(this).attr('id');

            //This is where the uploaded file will be read by
            reader.onload = function () {
                //Validating the uploaded file Format
                switch (ext) {
                    case 'jpg':
                    case 'png':
                    case 'pdf':
                    case 'jpeg':
                    case 'docx':
                    case 'doc':
                    case 'excel':
                    case 'xlsm':
                    case 'xls':
                    case 'xlsx':
                    case 'ods':
                    case 'zip':
                    case 'rar':
                        //Put the file data into an array
                        fileData[fileCount] = this.result;
                        var n = fileData[fileCount].indexOf(";base64,") + 8;

                        //To Get the base64 bytes, remove the first part of the dataurl and //this we need to feed to SharePoint
                        fileData[fileCount] = fileData[fileCount].substring(n);
                        fileCount++;
                        break;
                    case 'sizeExceed':
                        fileData[fileCount] = '';
                        fileName[fileCount] = '';
                        alert('File size exceeded');
                        break;
                    default:
                        fileData[fileCount] = '';
                        fileName[fileCount] = '';
                        alert('Invalid format');
                }
                var site = _spPageContextInfo.webAbsoluteUrl;
                $().SPServices({
                    operation: 'UpdateListItems',
                    async: false,
                    listName: 'ListName',
                    batchCmd: 'New',
                    webURL: site,
                    valuepairs: [[Column1, $scope.val], ["Column2", $scope.val1], ["Column3", $scope.val2],["Column4",$scope.val4]], 
                    completefunc: function (xData, Status) {
                        if (Status == 'success' && $(xData.responseXML).find('ErrorCode').text() == '0x00000000') {
                            currentitem = $(xData.responseXML).SPFilterNode("z:row").attr("ows_ID");
                             if (file) {
                                getFileBuffer(file).then(function (buffer) {
                                    var bytes = new Uint8Array(buffer);
                                    var content = new SP.Base64EncodedByteArray(); //base64 encoding
                                    for (var b = 0; b < bytes.length; b++) {
                                        content.append(bytes[b]);
                                    }

                                    $().SPServices({
                                        operation: "AddAttachment",
                                        listName: "'ListName'",
                                        listItemID: currentitem,
                                        fileName: file.name,
                                        webURL:site,
                                        attachment: content.toBase64String(),
                                        async: false,
                                        completefunc: function (xData, Status) {
                                            alert('file uploaded')
                                        }
                                    });

                                });

                             }
                            //alert('List item created with ID ' + currentitem);                          
                        } else alert('List item creation failed');
                    }
                });
           
            };

            reader.onabort = function () {
                alert("The upload was aborted.");
            };

            reader.onerror = function () {
                alert("An error occured while reading the file.");
            };
            reader.readAsDataURL(file);
        }
    }
    var getFileBuffer = function (file) {

        var deferred = $.Deferred();
        var reader = new FileReader();

        reader.onload = function (e) {
            deferred.resolve(e.target.result);
        }

        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }

        reader.readAsArrayBuffer(file);

        return deferred.promise();

    };

No comments:

Post a Comment