我有一个输入类型的文件,一旦用户单击以上传其图像,该过程 的上传开始,并显示该图像的缩略图,在chrome上正常工作,firefox出现问题,单击上传后没有缩略图显示,这是我用来执行此过程的代码:< / p>
var input = event.target;
// Instantiate FileReader
var reader = new FileReader();
reader.onload = function(){
TheFileContents = reader.result;
// Update the output to include the <img> tag with the data URL as the source
document.getElementById("img").src = TheFileContents;
};
// Produce a data URL (base64 encoded string of the data in the file)
// We are retrieving the first file from the FileList object
reader.readAsDataURL(input.files[0]);
答案 0 :(得分:0)
在您的示例中,如果要在reader.onload
在FileReader
上不是有效的方法。 reader
上添加事件,则可以像this那样添加事件:
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
我刚刚检查过,并且它在Firefox上正常工作。
答案 1 :(得分:0)
更新后的值为to onload by an event property:event.target.result
var input = event.target;
// Instantiate FileReader
var reader = new FileReader();
reader.onload = function(event){
var fileContent = event.target.result;
// Update the output to include the <img> tag with the data URL as the source
document.getElementById("img").src = fileContent;
};
// Produce a data URL (base64 encoded string of the data in the file)
// We are retrieving the first file from the FileList object
reader.readAsDataURL(input.files[0]);