How to Attach Multiple Files into SharePoint List Item Using SPServices and Also Validating on File Size and Format

Ahamed Fazil Buhari
 
Senior Developer
June 20, 2016
 
Rate this article
 
Views
23755

I had a requirement to upload Multiple Files into the SharePoint list item. I need to implement this using Jquery, SPServices and the html tag <input type="file"/>.And we need to allow only the file formats namely – (pdf, jpeg, doc, docx, excel, xlsm, xls, xlsx, .ods,.zip, .rar) and restrict all other formats, also the upload maximum size will be 5 MB not more than that for each file.

I come up with the below step by step approach to achieve this requirement.

Step 1: Creation of Browse Button Using <input type=’file’ /> Tag.

Below is the HTML tag, I’ve used to create the browse button and some more buttons for additional functionality. Please concentrate and look only at <input type=’file’ /> tag

 <td id="fileAttachTD">
         <span id="attach">
             <input type="file" id="attach1" name="FileUpload" />br />
             <input type="file" id="attach2" name="FileUpload" /><input type="button" id="btnRemove2" /><br />
             <input type="file" id="attach3" name="FileUpload" /><input type="button" id="btnRemove3" /><br />
         </span>
         <br />
         <span id="AddRemoveBtn">
             <input type="button" id="btnAdd" value="Add New Attachment" /><br />
             <p id="lblAttchInfo">
                 Maximum 10 attachments, allowed formats (pdf, jpeg, doc, docx, excel, xlsm, xls,xlsx,.ods, .zip, .rar) - Maximum file size allowed for per attachment 5MB</p>
         </span>
     </td>
 

The output for the above tag will be shown as below,

clip_image002

Step 2: Read the Uploaded Multiple files and keeping it in an Array using Jquery

Here the ‘input:file’ event function is called based on the <td> id fileAttachTD, so that this event will get triggered when any browse button is clicked under this <td>.

The Script itself has all the required comments. I don’t have much to explain about the script.

 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
 
 $('#fileAttachTD').on('change', 'input:file', function (event) {       
 
     //Getting the Target file
     var files = event.target.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');
             }
         };
 
         reader.onabort = function () {
             alert("The upload was aborted.");
         };
 
         reader.onerror = function () {
             alert("An error occured while reading the file.");
         };
         reader.readAsDataURL(file);
     }
 });
 

Step 3: Adding Attachments to the List Item using SPServices

Finally, uploading all the files into the list item using SPServices.

If the uploading of attachment needs to be done for the New List Item, then the below function should be called after the List Item is successfully created and then that Item ID should be passed as a parameter.

 //Function to Upload the Attachment, 
 //Parameter - itemID, List Item ID where the attachment needs to be uploaded
 function AddAttachments(itemID) {
 //Retrieving all the files which are available in an Array, Created this Array in //the above step(Step 2)
     for (var i = 0; i < fileCount; i++) {
         if (fileData[i] != '')
             $().SPServices({
                 operation: 'AddAttachment',
                 async: false,
                 listName: 'Name of the List',
                 listItemID: itemID,
                 fileName: fileName[i],
                 attachment: fileData[i],
                 completefunc: function (xData, Status) {
                 }
             });
     }
 }
 

Happy Coding,

Ahamed Buhari

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

Leave a comment