How can I show the image in the sweet alert I want to download?
The following code doesn't work for me. I want the image to appear in the swal (Sweet Alert) when the input is changed, but I don't know what is not working. I am getting the following error on the console:
Failed to execute'readAsDataURL' on 'FileReader': parameter 1 is not type 'Blob'
ENTRANCE
<input id="input" type="file" style="display:none;" onchange="muda()">
Script
<script>
function muda(){
var thefile = document.getElementById('input');
var reader = new FileReader();
reader.onloadend = function(){
var imagem = reader.result;
}
if(thefile){
reader.readAsDataURL(thefile);
}
swal({
title: "Esta é a imagem que pretende inserir?",
text: "<img src='"+imagem+"' style='width:150px;'>",
html:true,
});
}
</script>
UPDATE
With adaneo's answer, I was able to read the filename by adding .files[0];
, but I don't know how to get the path to the image now, I tried to put a variable named image as you can see in the code, but it turnsundefined
source to share
The argument you are passing thefile
is a DOM element, not a file.
You want to transfer the file, not the whole item
var thefile = document.getElementById('input').files[0];
This selects the first one (and only, since it doesn't have a "plural" set) and passes it to the FileReader
reader.onloadend
is asynchronous, you have to put your swal () function inside the callback
Here's another way to do it, without inline javascript
document.getElementById('input').addEventListener('change', function() {
var thefile = this.files[0];
var reader = new FileReader();
reader.onload = function() {
swal({
title: "Esta é a imagem que pretende inserir?",
text: "<img src='" + reader.result + "' style='width:150px;'>",
html: true,
});
}
reader.readAsDataURL(thefile);
}, false);
source to share
along with @adeneo's answer, I would like to add more about swal. According to the latest swal documentation, it should be as follows:
swal({
title: '<strong>HTML <u>example</u></strong>',
type: 'info',
html:
'You can use <b>bold text</b>, ' +
'<a href="//github.com">links</a> ' +
'and other HTML tags',
});
you can put anything in the html tag of course.
source to share