首页 > 解决方案 > 如何在 Jquery 中显示上传的图像?

问题描述

<html>
<head><script src = "/jquery.js"></script></head>

Test Image Upload
    <input type = "file" id = "chooseimage" name = "chooseimage" accept = ".jpg, .jpeg, .png" multiple><br>
    <input type = "button" id = "submitimages" value = "Send Image">
    <br>
<div id = "test"></div>

<script>
    $("#submitimages").click(function(){
        var imageinput = $("#chooseimage")[0].files[0];
        var reader = new FileReader();
        var a = reader.readAsDataURL(imageinput);
        reader.onload = function(e)(){};  // what do i do with this?
        $("#test").html(a);
    });
</script>
</html>

对于 Jquery,让我快速回顾一下我的思考过程。

1)我得到输入ID“chooseimage”并使用.files命令获取文件。我假设 .files[0] 意味着从 HTML 元素中选择第一个文件(但它只选择它,而不是实际读取它)?

2) 创建一个新的 FileReader()。我不太确定这是做什么的,我认为它可以让我......读取文件?

3)但是要先使用FileReader读取文件,我们需要将文件转换为base64编码的字符串,所以我们使用readAsDataURL进行转换。

4) 然后我用 reader.onload() 做一些事情,但我不确定这是做什么的。我正在阅读有关此的其他教程,他们都有,但没有解释它的作用。我阅读了 Mozilla 文档,但不太明白。到目前为止,我什么也没做。

5) 我想在 id 为“test”的 div 元素中显示 base64 字符串。我认为浏览器会自动将字符串解释为图像。无论哪种方式,它都没有显示任何内容。

有人可以引导我了解我所做的或不正确的理解以及我做错了什么吗?

标签: javascriptjquery

解决方案


看看这个,让我知道它是怎么回事。:)

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    
    reader.onload = function(e) {
      $('#imageShow').attr('src', e.target.result);
    }
    
    reader.readAsDataURL(input.files[0]);
  }
}

$("#imgPreview").change(function() {
  readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form runat="server">
  <input type='file' id="imgPreview" />
  <img id="imageShow" src="#" alt="your image" />
</form>


推荐阅读