我的 javascript Filereader 遇到问题,它返回错误 Uncaught TypeError: 无法在“FileReader”上执行“readAsDataURL”:参数 1 不是“Blob”类型。二分之一。有时它有效,但当我重复操作时,它会失败。
这是 HTML
<div id="upload-button" class="fpd-btn-raised fpd-secondary-bg-color fpd-secondary-text-color">
<i class="fpd-icon-file-upload"></i><span>Insérer votre image</span>
</div>
<input type="file" id="my-custom-design-upload" class="btn btn-success" style="display:none;">
这是 JavaScript
这是一个 div 按钮,单击时会触发输入字段的单击
$('#upload-button').click(function(){
$('#my-custom-design-upload').trigger('click');
return false;
});
调用文件Reader的函数
function readfichier(e) {
if(window.FileReader) {
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
var image = new Image;
image.src = e.target.result;
image.onload = function() {// Do something}
}
}
以及对该函数的调用
document.getElementById('my-custom-design-upload').addEventListener('change', readfichier, false);
有什么想法吗?谢谢
最佳答案
您不需要创建新图像
,您应该监听readAsDataURL
方法的loadend
事件,该事件将提供您可以使用 Base64 编码的数据字符串。
FileReader.readAsDataURL()
The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a URL representing the file's data as a base64 encoded string.
还要确保您确实有一个文件,甚至可以检查file.type
。既然您正在尝试对图像执行某些操作,为什么不检查您是否有图像呢?这绝不是某种验证,但如果它不是图像,您可能不需要显示任何内容或执行任何操作。
这是一个示例。
var img = $('img');
img.css('display', 'none');
$('#upload-button').click(function(){
$('#my-custom-design-upload').trigger('click');
return false;
});
function readfichier(e) {
if(window.FileReader) {
var file = e.target.files[0];
var reader = new FileReader();
if (file && file.type.match('image.*')) {
reader.readAsDataURL(file);
} else {
img.css('display', 'none');
img.attr('src', '');
}
reader.onloadend = function (e) {
img.attr('src', reader.result);
img.css('display', 'block');
}
}
}
document.getElementById('my-custom-design-upload').addEventListener('change', readfichier, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="upload-button" class="fpd-btn-raised fpd-secondary-bg-color fpd-secondary-text-color">
<i class="fpd-icon-file-upload"></i><span>Insérer votre image</span>
</div>
<input type="file" id="my-custom-design-upload" class="btn btn-success" style="display:none;" />
<img src="" height="200" />
关于javascript - 未捕获的类型错误 : Failed to execute 'readAsDataURL' on 'FileReader' : parameter 1 is not of type 'Blob' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32508191/