I\'ve got a problem with a javascript Filereader which returns the error Uncaught TypeError: Failed to execute \'readAsDataURL\' on \'FileReader\': parameter 1 is not of type \'
You have to trigger change event on input field. then you will receive file.
$('#upload-button').click(function(){
$('#my-custom-design-upload').trigger('change');
return false;
});
You need to make sure file has a value (not undefined
or null
).
At the top of imageFunction
:
if(!file) {
// handle error condition and return
}
You do not need to create a new Image
and you should be listening for the loadend
event of the readAsDataURL
method, which will provide you with a base64 encoded string of your data.
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.
Also make sure you actually have a file, and maybe even check the file.type
. Since you are trying to do something with an image, why not check if you have an image. Which in no way is some kind of validation, but if it is not an image, you may not need to show anything or do anything.
Here is an example.
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" />
i was getting a similar error when i would click the input but then instead of choosing an attachment, clicking cancel. so if I just wrapped the readAsDataURL call with an if statement checking if the file existed, it fixed it. see below.
onSelectFile(event) {
let reader = new FileReader();
reader.onload = function(){
let output: any = document.getElementById('blah');
output.src = reader.result;
}
if(event.target.files[0]){
reader.readAsDataURL(event.target.files[0]);
}
}