Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I show an image in sweet alert that I want to upload?

I have the following code not working. I want the image to appear in a swal (Sweet Alert) when the input is changed, but I don't know what's not working. I get the following error on console:

Failed to execute'readAsDataURL' on 'FileReader': parameter 1 is not type 'Blob'

INPUT

<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 response, I managed to read the file name adding .files[0]; but I don't know how to get the image path now, I tried to put a variable named image as you can see in the code but it turns undefined

like image 455
I_like_trains Avatar asked Aug 08 '17 15:08

I_like_trains


People also ask

How do I add sweet alert in HTML?

All you have to do is enable the html variable to true.. I had same issue, all i had to do was html : true , var hh = "<b>test</b>"; swal({ title: "" + txt + "", text: "Testno sporocilo za objekt " + hh + "", html: true, confirmButtonText: "V redu", allowOutsideClick: "true" });

How do I remove the OK button from sweet alert?

Instead, you can set buttons: true to show both buttons, or buttons: false to hide all buttons. By default, only the confirm button is shown. This is the best answer!


1 Answers

The argument you're passing in, thefile, is a DOM element, not a file.

You want to pass the file, not the entire element

var thefile = document.getElementById('input').files[0];

That selects the first (and only, as it doesn't have "multiple" set) file 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 this, without the 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);
like image 77
adeneo Avatar answered Sep 21 '22 17:09

adeneo