如何在甜蜜警报中显示我要上传的图像?

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

我有以下代码不工作。当输入更改时,我希望图像出现在 swal(Sweet Alert)中,但我不知道什么不起作用。我在控制台上收到以下错误:

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

输入

<input id="input" type="file" style="display:none;" onchange="muda()">

脚本

<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>

更新

通过 adaneo 响应,我设法读取了添加 .files[0]; 的文件名,但我现在不知道如何获取图像路径,我尝试放置一个名为 image 的变量,如您在代码,但它变成 undefined

您传递的参数 thefile 是 DOM 元素,而不是文件。

您想传递文件,而不是整个元素

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

选择第一个 (并且仅选择,因为它没有设置 "multiple") 文件并将其传递给 FileReader

reader.onloadend 是异步的,你必须把你的 swal() 函数放在回调中

这是另一种方法,没有内联 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);
<div onclick="imgClick(this)">
   <img src="image/img1.jpg" width="150px">

</div>

<script>
function imgClick(e){
    var src = $(e).find('img').attr('src');
    swal({
           title: "Hello World",
           text: "<img src='"+src+"' style='width:150px;'>",
           content:true,
        });
}

</script>

连同@adeneo 的回复,我想补充更多关于 swal 的内容。根据最新的 swal 文档,应该如下

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',
});

您当然可以在 html 标签中放置任何内容。