javascript - 如何在 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 字符串。我认为浏览器会自动将字符串解释为图像。无论哪种方式,它都没有显示任何内容。
有人可以引导我了解我所做的或不正确的理解以及我做错了什么吗?
解决方案
看看这个,让我知道它是怎么回事。:)
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>
推荐阅读
- javascript - JQuery:在 HTML 上使用 .text() ,警报在消息中显示奇怪的文本
- mdriven - 如何在电子邮件中添加嵌入对象?
- node.js - 有没有办法用 Google Script 抓取 Javascript 内容?
- javascript - execCommand 不适用于选定的文本
- powershell - Jenkins 和 Powershell:使用“-Wait”参数启动进程
- javascript - 在js中访问当前页面的标题
- angular - 窗口样式的角度问题
- python - 不改变变量
- angular - docker 容器中的前端和后端
- wordpress - WooCommerce 自定义常规字段 - 添加到电子邮件