Search code examples
javascriptjquerysharepoint-2010

File Upload Using jQuery not working in IE


I'm having a difficult time trying to get the below code to work in IE. The code works as expected in Firefox, Chrome, and Edge; but not in IE. I would ignore it not working in IE, but it's the default browser used at work.

The code is written to upload multiple files into a specific SharePoint document library. I got the code from this post https://social.msdn.microsoft.com/Forums/office/en-US/bb590f35-da1b-4905-baa0-fb85a275abf6/multiple-files-upload-in-document-library-using-javascript-object-model?forum=appsforsharepoint. It's the last post, and it does work great in the mentioned browsers. Any suggestions on how to get it to work in IE will greatly be appreciated. Thank you in advance.

Script is below:

jQuery(document).ready(function() {

    fileInput = $("#getFile");
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);
});

function registerClick() {
    //Register File Upload Click Event  
    jQuery("#addFileButton").on('click', readFile);
}
var arrayBuffer;

function readFile() {
    //Get File Input Control and read th file name  
    var element = document.getElementById("getFile");
    var fileCount = element.files.length;
    var filesUploaded = 0;
    for (var i = 0; i < fileCount; i++) {
        let file = element.files[i];
        var reader = new FileReader();
        reader._NAME = element.files[i].name
        reader.onload = function(e) {
            let fileactualName = e.target._NAME;
            uploadFile(e.target.result, fileactualName);
        }
        reader.onerror = function(e) {
            alert(e.target.error);
        }
        reader.readAsArrayBuffer(file);
    }
}

function uploadFile(arrayBuffer, fileName) {
    //Get Client Context,Web and List object.  
    var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle('Comms Shared Files');
    //Convert the file contents into base64 data  
    var bytes = new Uint8Array(arrayBuffer);
    var i, length, out = '';
    for (i = 0, length = bytes.length; i < length; i += 1) {
        out += String.fromCharCode(bytes[i]);
    }
    var base64 = btoa(out);
    //Create FileCreationInformation object using the read file data  
    var createInfo = new SP.FileCreationInformation();
    createInfo.set_content(base64);
    createInfo.set_url(fileName);
    //Add the file to the library  
    var uploadedDocument = oList.get_rootFolder().get_files().add(createInfo)
    //Load client context and execcute the batch  
    clientContext.load(uploadedDocument);
    clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
}

function QuerySuccess() {
    alert('File Uploaded Successfully.');
}

function QueryFailure(sender, args) {
    console.log('Request failed with error message - ' + args.get_message());
}

Solution

  • In SharePoint 2010, we can use SharePoint designer to open the v4.master(defualt), and add "IE=11" in "X-UA-Compatible".

    <meta http-equiv="X-UA-Compatible" content="IE=8,IE=11"/>
    

    enter image description here

    In SharePoint 2013/2016/2019/online, we can use REST API to upload the files to document library with jQuery code.

    <input id="inputFile" type="file" multiple="multiple"/>
    <input id="uploadDocumentButton" type="Button" value="Upload Document">
    <script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    var libraryTitle="DL";
    $(function(){
        $("#uploadDocumentButton").click(function () {
            if (document.getElementById("inputFile").files.length === 0) {
                alert("Select a file!");
                return;
            }
            for(var i = 0; i < document.getElementById("inputFile").files.length; i++){         
                var file = document.getElementById("inputFile").files[i];
                uploadFileSync(libraryTitle, file.name, file);
            }
            alert("upload complete.");
        });     
    });
    function uploadFileSync(folderUrl, filename, file){
         var reader = new FileReader();
         reader.onloadend = function(evt){
             if (evt.target.readyState == FileReader.DONE){
                 var buffer = evt.target.result;
    
                 var completeUrl =_spPageContextInfo.webAbsoluteUrl
                   + "/_api/web/GetFolderByServerRelativeUrl('"+folderUrl+"')/Files/add(url='" + filename + "',overwrite=true)";
    
                $.ajax({
                     url: completeUrl,
                     type: "POST",
                     data: buffer,
                     async: false,
                     processData: false,
                     headers: {
                         "accept": "application/json;odata=verbose",
                         "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                         "content-length": buffer.byteLength
                     },
                     complete: function (data) {
                        //alert("upload complete.");
                        //console.log(data.responseJSON.d.ServerRelativeUrl);
                     },
                     error: function (err) {
                         alert('failed');
                     }
                 });
    
            }
         };
         reader.readAsArrayBuffer(file);
    }
    </script>