Tuesday, December 12, 2017

Uploading multiple files to SharePoint list as attachment using SharePointPlus

Uploading multiple files to SharePoint list as attachment using SharePointPlus
Step 1: Create an custom list and add an test item.
Step 2: Create an "FileUpload.html" and add below code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>SharePoint Plus</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharepointplus@4.0.0/nanoajax/nanoajax.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharepointplus@4.0.0/sharepointplus-4.0.min.js"></script>
    <script type="text/javascript">
        var fileData = new Object;
        var objFileContent = new Object;
        var objFileName = new Object;
        var arrayGuid = [];
        $(document).ready(function () {
            myAttachments();
        });
        function createGuid() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }
        function remove(array, element) {
            const index = array.indexOf(element);
            if (index !== -1) {
                array.splice(index, 1);
            }
        }
        function deleteFileAttachment(divID) {
            console.log(divID);
            $("#" + divID + "").remove();
            delete fileData["" + divID + ""];
            delete objFileName["" + divID + ""];
            remove(arrayGuid, "" + divID + "");
        }
        function uploadListAttachment(content, objFileName) {
            $SP().list("CustomList01").addAttachment({
                ID: 3,
                filename: objFileName,
                attachment: content.toBase64String(),
                after: function (fileURL) {
                    console.log(fileURL);
                }
            });
        }
        function FileUpload() {
            for (i = 0; i < Object.keys(fileData).length; i++) {
                var bytes = new Uint8Array(fileData[arrayGuid[i]]);
                if (bytes.length > 0) {
                    var content = new SP.Base64EncodedByteArray();
                    for (var b = 0; b < bytes.length; b++) {
                        content.append(bytes[b]);
                    }
                    objFileContent[arrayGuid[i]] = content;
                }
            }
            for (i = 0; i < Object.keys(objFileContent).length; i++) {
                console.log("objFileContent : " + objFileContent[arrayGuid[i]]);
                console.log("objFileName : " + objFileName[arrayGuid[i]]);
                if (objFileContent[arrayGuid[i]] != null && objFileName[arrayGuid[i]] != null) {
                    uploadListAttachment(objFileContent[arrayGuid[i]], objFileName[arrayGuid[i]]);
                }
            };
        }
        function myAttachments() {
            $("#my-attachments").change(function () {
                var x = document.getElementById("my-attachments");
                var txt = "";
                if ('files' in x) {
                    if (x.files.length == 0) {
                        txt = "Select one or more files.";
                    } else {
                        for (var i = 0; i < x.files.length; i++) {
                            arrayGuid.push(createGuid());
                            txt += "<div id='" + arrayGuid[arrayGuid.length - 1] + "'><img onclick=\"deleteFileAttachment('" + arrayGuid[arrayGuid.length - 1] + "')\" src='https://sharepointonline01.sharepoint.com/sites/dev2/SiteAssets/fileupload/delete_file.png' alt='Delete' width='10' height='10'>";
                            var file = x.files[i];
                            if ('name' in file) {
                                txt += "  " + file.name + " ";
                            }
                            if ('size' in file) {
                                txt += "(" + file.size + " bytes)</div>";
                            }
                        }
                    }
                }
                else {
                    if (x.value == "") {
                        txt += "Select one or more files.";
                    } else {
                        txt += "The files property is not supported by your browser!";
                        txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
                    }
                }
                $('#demo').append(txt);
                var j = 0, k = $(this)[0].files.length;
                for (var i = 0; i < k; i++) {
                    var reader = new FileReader();
                    reader.onloadend = function (evt) {
                        if (evt.target.readyState == FileReader.DONE) {
                            fileData[arrayGuid[arrayGuid.length - k + j]] = evt.target.result;
                            j++;
                            if (j == k) {
                                console.log('All files read');
                            }
                        }
                    };
                    reader.readAsArrayBuffer($(this)[0].files[i]);
                    objFileName[arrayGuid[Object.keys(objFileName).length]] = $(this)[0].files[i].name;
                }
            });
        }
    </script>
</head>
<body>
    <input id="my-attachments" type="file" multiple fileread="run.AttachmentData" fileinfo="run.AttachmentInfo" style="display: none;" />
    <input type="button" value="Chose Files..." onclick="document.getElementById('my-attachments').click();" />
    <button type="button" onclick="FileUpload()">File Upload</button>
    <div id="demo"></div>
</body>
</html>
===========================================
Using "jquery.multifile.min.js" code  V.1.0
===========================================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>SharePoint Plus</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharepointplus@4.0.0/nanoajax/nanoajax.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharepointplus@4.0.0/sharepointplus-4.0.min.js"></script>
    <script type="text/javascript" src="https://sharepointonline01.sharepoint.com/sites/dev2/SiteAssets/fileupload/jquery.multifile.min.js"></script>
    <script type="text/javascript">
var fileData = new Object;
    var objFileContent = new Object;
    var objFileName = new Object;
$(document).ready(function () {
$('#my-attachments').MultiFile({     
    onFileRemove: function(element, value, master_element) {
    myAttachments(element, value, master_element);
    },
    afterFileRemove: function(element, value, master_element) {
    myAttachments(element, value, master_element);
    },
    onFileAppend: function(element, value, master_element) {},
    afterFileAppend: function(element, value, master_element) {
    myAttachments(element, value, master_element);
    },
    onFileSelect: function(element, value, master_element) {},
    afterFileSelect: function(element, value, master_element) {},
    onFileInvalid: function(element, value, master_element) {},
    onFileDuplicate: function(element, value, master_element) {},
    onFileTooMany: function(element, value, master_element) {},
    onFileTooBig: function(element, value, master_element) {},
    onFileTooMuch: function(element, value, master_element) {}
  });
     });     
    function myAttachments(element, value, master_element) {
    fileData = [];
    objFileName = [];
if(master_element.files.length>0) {
master_element.files.forEach(function(file,index) {
objFileName[index] = file.name;
var reader = new FileReader();
reader.onload = function(){
fileData[index] = reader.result;
};
reader.readAsArrayBuffer(file);
});
}
}
function FileUpload() {
for (i = 0; i < Object.keys(fileData).length; i++) {
            var bytes = new Uint8Array(fileData[i]);
            if (bytes.length > 0) {
                var content = new SP.Base64EncodedByteArray();
                for (var b = 0; b < bytes.length; b++) {
                    content.append(bytes[b]);
                }
                objFileContent[i] = content;
            }
        }
        for (i = 0; i < Object.keys(objFileContent).length; i++) {
uploadListAttachment(objFileContent[i], objFileName[i]);  
}          
}
function uploadListAttachment(content, objFileName) {
        $SP().list("CustomList01").addAttachment({
            ID: 4,
            filename: objFileName,
            attachment: content.toBase64String(),
            after: function (fileURL) {
                console.log("fileURL: " +fileURL);
            }
        });
    }
</script>
</head>
<body>
    <input id="my-attachments" type="file" />
    <button type="button" onclick="FileUpload()">File Upload</button>
</body>
</html>
===========================================
Using "jquery.multifile.min.js" code V.2.0
===========================================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>SharePoint Plus</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharepointplus@4.0.0/nanoajax/nanoajax.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharepointplus@4.0.0/sharepointplus-4.0.min.js"></script>
    <script type="text/javascript" src="https://sharepointonline01.sharepoint.com/sites/dev2/SiteAssets/fileupload/jquery.multifile.min.js"></script>
    <script type="text/javascript">
        var objmaster_element = "";
         var bytes = "";
        $(document).ready(function () {
            $('#my-attachments').MultiFile({
                onFileRemove: function (element, value, master_element) {
                    objmaster_element = master_element;
                },
                afterFileRemove: function (element, value, master_element) {
                    objmaster_element = master_element;
                },
                onFileAppend: function (element, value, master_element) { },
                afterFileAppend: function (element, value, master_element) {
                    objmaster_element = master_element;
                },
                onFileSelect: function (element, value, master_element) { },
                afterFileSelect: function (element, value, master_element) { },
                onFileInvalid: function (element, value, master_element) { },
                onFileDuplicate: function (element, value, master_element) { },
                onFileTooMany: function (element, value, master_element) { },
                onFileTooBig: function (element, value, master_element) { },
                onFileTooMuch: function (element, value, master_element) { }
            });
        });
        function FileUpload() {
            if (objmaster_element.files.length > 0) {
                objmaster_element.files.forEach(function (file, index) {
                    var reader = new FileReader();
                    reader.onload = function () {
                         bytes = new Uint8Array(reader.result);
                    };
                    reader.readAsArrayBuffer(file);                   
                    if (bytes.length > 0) {
                        var content = new SP.Base64EncodedByteArray();
                        for (var b = 0; b < bytes.length; b++) {
                            content.append(bytes[b]);
                        }
                        $SP().list("CustomList01").addAttachment({
                            ID: 4,
                            filename: file.name,
                            attachment: content.toBase64String(),
                            async: true,
                            after: function (fileURL) {
                                console.log("fileURL: " + fileURL);                                
                            }
                        });
                    }
                });
            }            
        }
    </script>
</head>
<body>
    test1
    <input id="my-attachments" type="file" />
    <button type="button" onclick="FileUpload()">File Upload</button>
</body>

</html>
===========================================
Using "jquery.multifile.min.js" code V.3.0
===========================================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>SharePoint Plus</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharepointplus@4.0.0/nanoajax/nanoajax.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharepointplus@4.0.0/sharepointplus-4.0.min.js"></script>
    <script type="text/javascript" src="https://sharepointonline01.sharepoint.com/sites/dev2/SiteAssets/fileupload/jquery.multifile.min.js"></script>
    <script type="text/javascript">
        var objmaster_element = "";
        var bytes = "";
        $(document).ready(function () {
            $('#my-attachments').MultiFile({
                onFileRemove: function (element, value, master_element) {
                    objmaster_element = master_element;
                },
                afterFileRemove: function (element, value, master_element) {
                    objmaster_element = master_element;
                },
                onFileAppend: function (element, value, master_element) { },
                afterFileAppend: function (element, value, master_element) {
                    objmaster_element = master_element;
                },
                onFileSelect: function (element, value, master_element) { },
                afterFileSelect: function (element, value, master_element) { },
                onFileInvalid: function (element, value, master_element) { },
                onFileDuplicate: function (element, value, master_element) { },
                onFileTooMany: function (element, value, master_element) { },
                onFileTooBig: function (element, value, master_element) { },
                onFileTooMuch: function (element, value, master_element) { }
            });
        });
        function FileUpload() {
            if (objmaster_element.files.length > 0) {
                var promises = [];
                objmaster_element.files.forEach(function (file, index) {
                    var deferred = $.Deferred();
                    getFileBuffer(file).then(
                      function (buffer) {
                          getContent(buffer).then(
                              function (content) {
                                  $SP().list("CustomList01").addAttachment({
                                      ID: 4,
                                      filename: file.name,
                                      attachment: content.toBase64String(),
                                      async: false,
                                      completefunc: function (xData, Status) {
                                          deferred.resolve();
                                      }
                                  });
                                  promises.push(deferred);
                              });
                      },
                      function (err) {
                          deferred.reject(err);
                      });
                    return deferred.promise();
                });
                return $.when.apply(undefined, promises).promise();            }
        }
        function getFileBuffer(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();
        }
        function getContent(buffer) {
            var deferred = $.Deferred();
            var bytes = new Uint8Array(buffer);
            var content = new SP.Base64EncodedByteArray();
            for (var b = 0; b < bytes.length; b++) {
                content.append(bytes[b]);
            }
            deferred.resolve(content);
            return deferred.promise();
        }
    </script>
</head>
<body>
    <input id="my-attachments" type="file" />
    <button type="button" onclick="FileUpload()">File Upload</button>
</body>
</html>
===========================================
=====================================
<!-- Using "jquery.multifile.min.js" and JQuery Ajax code V.4.0 -->
<html>
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharepointplus@4.0.0/nanoajax/nanoajax.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharepointplus@4.0.0/sharepointplus-4.0.min.js"></script>
    <script type="text/javascript" src="/sites/dev2/SiteAssets/fileupload/jquery.multifile.min.js"></script>
    <script type="text/javascript">
        var ID = 4;
        var listname = "CustomList01";
        var array_filename = [];
        var array_buffer = [];
        $(document).ready(function () {
            $('#my-attachments').MultiFile({
                onFileRemove: function (element, value, master_element) {
                    myAttachments(element, value, master_element);
                },
                afterFileRemove: function (element, value, master_element) {
                    myAttachments(element, value, master_element);
                },
                onFileAppend: function (element, value, master_element) { },
                afterFileAppend: function (element, value, master_element) {
                    myAttachments(element, value, master_element);
                },
                onFileSelect: function (element, value, master_element) { },
                afterFileSelect: function (element, value, master_element) { },
                onFileInvalid: function (element, value, master_element) { },
                onFileDuplicate: function (element, value, master_element) { },
                onFileTooMany: function (element, value, master_element) { },
                onFileTooBig: function (element, value, master_element) { },
                onFileTooMuch: function (element, value, master_element) { }
            });
            $("#btnUpload").click(function () {
                fileUpload();
            });
        });
        function myAttachments(element, value, master_element) {
            array_filename = [];
            array_buffer = [];
            master_element.files.forEach(function (file, index) {
                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();
                };
                getFileBuffer(file).then(function (buffer) {
                    array_filename.push(file.name);
                    array_buffer.push(buffer);
                });
            });
        }
        function fileUpload() {
            for (let i = 0, p = Promise.resolve(); i < array_filename.length; i++) {
                p = p.then(_ => new Promise(resolve =>
                setTimeout(function () {
                    var filename = array_filename[i];
                    var buffer = array_buffer[i];
                    var request = $.ajax({
                        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + ID + ")/AttachmentFiles/add(FileName='" + filename + "')",
                        method: 'POST',
                        data: buffer,
                        processData: false,
                        headers: {
                            "Accept": "application/json; odata=verbose",
                            "content-type": "application/json; odata=verbose",
                            "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
                            //"content-length": buffer.byteLength
                        },
                        async: true,
                        success: function (data, status, xhr) {},
                        error: function (xhr, status, error) {},
                        complete: function() {}
                    });
                    resolve(request);
                }, 1000)
                ));
            }
        }
    </script>
</head>
<body>
    <div>
        <input id="my-attachments" type="file" fileread="run.AttachmentData" fileinfo="run.AttachmentInfo" />
        <input id="btnUpload" type="button" value="upload" />
    </div>
</body>
</html>
=====================================
Step 3: Upload "FileUpload.html" this file to site assets.
Step 4: Create an WebPart page and add content editor webpart.
Step 5: Test application.

No comments:

Post a Comment

Featured Post

Mention a Channel or Team – Power Automate

Mention a Channel or Team – Power Automate graph.microsoft.com/v1.0/teams/{teamId}/channels/{channelId}/messages Channel: ---------- {   ...

Popular posts