我正在爲此工作6個小時,我無法弄清楚。未被捕獲的DOMException:未能在'FileReader'上執行'readAsDataURL':該對象已經忙於讀取Blob。(...)
我想創建一個網站,我在其中選擇一個圖像文件夾,然後將它們顯示在我的文檔中。我得到第一張圖片,然後在控制檯中出現以下錯誤。
未捕獲拋出:DOMException:未能執行「readAsDataURL」上「的FileReader」:對象是已經忙於閱讀的斑點(...)
我認爲問題是由於引起了我的for循環,因爲的FileReader是異步。但我需要循環遍歷整個數組,所以我做錯了什麼?
我加載文件(「將檢查以確保我以後只能得到圖像」),放入數組中,然後每次讀取一個文件。 在將我的代碼分解爲函數之前,我在一個函數中做了所有事情,並且它可以工作!我包含HTML +原始和當前的JS代碼。 感謝您花時間看到這一點。
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tiled Image Viewer</title>
<script src="js/tiv.js"></script>
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="main-wrap">
<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory name="myFiles"
onchange="readAndShowFiles();" multiple/>
<span id="list"></span>
</form>
</div>
</body>
</html>
的Javascript原文:
function readAndShowFiles() {
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Have to check that this is an image though
// using the file.name TODO
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img src="', e.target.result,
'" title="', escape(file.name), '">'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
的Javascript電流:
function readAndShowFiles() {
console.log("Checkpoint2"); //test
var tiv = new tivAPI();
var array = tiv.getLoadedImages();
tiv.showLoadedImages(array);
}
function tivAPI(){
var imagesarray = new Array();
return{
loadImages: function(){
console.log("Loading Files"); //test
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Have to check that this is an image though
// using the file.name TODO
}
console.log(files.length); //test
return files;
},
getLoadedImages: function(){
imagesarray = this.loadImages();
console.log("Returning Files"); //test
console.log(imagesarray.length);
return imagesarray;
},
showLoadedImages: function(elem){
console.log("Showing Files"); //test
var files = elem;
var reader = new FileReader();
// Closure to capture the file information.
for (var i = 0; i < files.length; i++) {
var file = files[i];
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img src="', e.target.result,
'" title="', escape(file.name), '">'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
};
}