我需要检索存储在本地文件系统中的一组图像的尺寸和缩略图。我没有缩略图的问题,但检索尺寸有点问题。它仅在所有尝试的三分之一或一半中起作用。如何让它更可靠地工作?
function handleFileSelect(evt) {
let files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (const file of files) {
// Only process image files.
if (!file.type.match('image.*')) {
continue;
}
let reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
let image = new Image();
image.src = this.result;
// Render thumbnail.
let item = document.createElement('li');
item.innerHTML = `<img class="thumb" src="${e.target.result}" title="${escape(theFile.name)}"/>
<p>name: ${theFile.name}</p>
<p>width: ${image.width} px</p>
<p>height: ${image.height} px</p>`;
document.getElementById('list').insertBefore(item, null);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
&#13;
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
ul {
list-style-type: none;
}
p {
font-family: sans;
font-size: 10px;
margin: 0;
}
&#13;
<input type="file" id="files" name="files" multiple>
<ul id="list"></ul>
&#13;
答案 0 :(得分:0)
关键点似乎是将FileReader(reader.onload
)结果(e.target.result
)传递给image.onload
函数。有了它,它按预期工作。我希望我能说这是关于正确回调的用法。
function handleFileSelect(evt) {
let files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (const file of files) {
// Only process image files.
if (!file.type.match('image.*')) {
continue;
}
// Create new Filereader object
let reader = new FileReader();
// Closure to capture the file information
reader.onload = (function(theFile) {
return function(e) {
let item = document.createElement('li');
// Create new Image object
let image = new Image();
// Assign the Image object’s onload logic, everything happens here
image.onload = function() {
// Create elements, use Image object’s properties
item.innerHTML = `<img class="thumb" src="${e.target.result}" title="${escape(theFile.name)}"/>
<p>name: ${theFile.name}</p>
<p>width: ${image.width} px</p>
<p>height: ${image.height} px</p>`;
document.getElementById('list').insertBefore(item, null);
}
// Load the image
image.src = this.result;
};
})(file);
// Read in the image file as a data URL
reader.readAsDataURL(file);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
&#13;
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
ul {
list-style-type: none;
}
p {
font-family: sans;
font-size: 10px;
margin: 0;
}
&#13;
<input type="file" id="files" name="files" multiple>
<ul id="list"></ul>
&#13;