Javascript-FileReader如何在多个文件中一次读取和处理每个文件

时间:2018-06-21 23:51:33

标签: javascript ajax filereader onload

我正在尝试让用户删除多个excel文件,并从每个文件中提取所需的值,然后一次将其上传到网站“一个文件”。

我的代码不起作用,我认为这是由于回调问题引起的。

有人可以帮忙吗?

编辑:我还添加了我的uploadFile函数。非常感谢您的帮助。

for(var i = 0; i < fileList.length; i++) {
            //console.log(fileList[i]["file"]);
            var reader = new FileReader();

            var f = fileList[i]["file"];
            //var fName = fileList[i]["fileName"];
            var excelObject = fileList[i];

            reader.onload = function(ev) {

                var data = ev.target.result;
                if(!rABS) data = new Uint8Array(data);

                var wb = XLSX.read(data, {type: rABS ? 'binary' : 'array'});

                var einAddress = "B3";
                var engCodeAddress = "B1";
                var goAddress = "B2";
                var errMsg = tabName + " tab or required value is missing";

                    // Worksheet with the necessary info
                try{
                    var ws =  wb.Sheets[tabName];
                    var ein_cell = ws[einAddress];
                    ein = (ein_cell ? ein_cell.v.toString() : undefined);

                    var eng_cell = ws[engCodeAddress];
                    engCode = (eng_cell ? eng_cell.v.toString() : undefined);

                    var go_cell = ws[goAddress];
                    goLocator = (go_cell ? go_cell.v.toString() : undefined);

                    if(ein == undefined || engCode == undefined || goLocator == undefined){
                        hasValues = false;
                    }

                    excelObject["EngagementCode"] = engCode;
                    excelObject["GoSystem"] = goLocator;
                    excelObject["EIN"] = ein;

                    if(hasValues && isValid){
                        uploadFile(fileList[i], userInfo);
                    } else {
                        noValueErrorHandler(errMsg);
                    }

                } catch(err){
                    hasValues = false;
                }

            };

            if(rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);

        } 


function uploadFile(f, userInfo) {

// Define the folder path for this example.
var serverRelativeUrlToFolder = listName;

// Get info of the file to be uploaded
var file = f;
var fileInput = file["file"];
var newName = file["fileName"];
var ein = file["EIN"];
var engCode = file["EngagementCode"];
var email = userInfo;
var goLocator = file["GoSystem"];
console.log("file: " + file);

// Get the server URL.
var serverUrl = _spPageContextInfo.siteAbsoluteUrl + "/StatusTracker";

// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileInput);
getFile.done(function (arrayBuffer) {

    // Add the file to the SharePoint folder.
    var addFile = addFileToFolder(arrayBuffer, newName);
    addFile.done(function (file, status, xhr) {

        // Get the list item that corresponds to the uploaded file.
        var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
        getItem.done(function (listItem, status, xhr) {

            // Change the display name and title of the list item.
            var changeItem = updateListItem(listItem.d.__metadata);
            changeItem.done(function (data, status, xhr) {
                processedCount += 1;
                if (processedCount < fileCount) {

                    uploadFile(fileList[processedCount], email);

                } else if (processedCount == fileCount){
                    $("#dropbox").text("Done, drop your next file");
                    $("#ADMNGrid").data("kendoGrid").dataSource.read();
                    fileList = [];
                    alert("Total of " + processedCount + " items are processed!");
                }



                // Refresh kendo grid and change back the message and empty fileList
                //$("#dropbox").text("Drag your Fund/Lower Tier workpaper here ...");
                //location.reload(true);

            });
            changeItem.fail(onError);
        });
        getItem.fail(onError);
    });
    addFile.fail(onError);
});
getFile.fail(onError);

1 个答案:

答案 0 :(得分:2)

您可以将整个内容放入async函数中,并在每次迭代时将awaitPromise中的内容放入其中,从而强制以串行方式处理文件。您没有发布uploadFile,但是如果返回Promise,则async fn() { for (var i = 0; i < fileList.length; i++) { await new Promise((resolve, reject) => { //console.log(fileList[i]["file"]); var reader = new FileReader(); var f = fileList[i]["file"]; //var fName = fileList[i]["fileName"]; var excelObject = fileList[i]; reader.onload = function(ev) { var data = ev.target.result; if (!rABS) data = new Uint8Array(data); var wb = XLSX.read(data, { type: rABS ? 'binary' : 'array' }); var einAddress = "B3"; var engCodeAddress = "B1"; var goAddress = "B2"; var errMsg = tabName + " tab or required value is missing"; // Worksheet with the necessary info try { var ws = wb.Sheets[tabName]; var ein_cell = ws[einAddress]; ein = (ein_cell ? ein_cell.v.toString() : undefined); var eng_cell = ws[engCodeAddress]; engCode = (eng_cell ? eng_cell.v.toString() : undefined); var go_cell = ws[goAddress]; goLocator = (go_cell ? go_cell.v.toString() : undefined); if (ein == undefined || engCode == undefined || goLocator == undefined) { hasValues = false; } excelObject["EngagementCode"] = engCode; excelObject["GoSystem"] = goLocator; excelObject["EIN"] = ein; if (hasValues && isValid) { uploadFile(fileList[i], userInfo) .then(resolve); } else { noValueErrorHandler(errMsg); reject(); } } catch (err) { hasValues = false; reject(); } }; if (rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f); }); } } 可以解决,您可以执行以下操作:

optionsID0EYE