HTML5图片上传预览

HTML5实现图片的上传预览,需要使用FileReader对象。

FileReader: The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

也就是说,使用FileReader对象先读取用户需要上传的图片,这个时候,图片是保存在浏览器中的,然后通过设置img元素的src,来预览图片,方法很简单。

在使用FileReader时需要先弄明白其Event handlers和方法。

Event handlers
Event handler描述
FileReader.onabortA handler for the abort event. This event is triggered each time the reading operation is aborted.
FileReader.onerrorA handler for the error event. This event is triggered each time the reading operation encounter an error.
FileReader.onloadA handler for the load event. This event is triggered each time the reading operation is successfully completed.
FileReader.onloadstartA handler for the loadstart event. This event is triggered each time the reading is starting.
FileReader.onloadendA handler for the loadend event. This event is triggered each time the reading operation is completed (either in success or failure).
FileReader.onprogressA handler for the progress event. This event is triggered while reading a Blob content.
Metchods
Method描述
FileReader.abort()Aborts the read operation. Upon return, the readyState will be DONE.
FileReader.readAsArrayBuffer()Starts reading the contents of the specified Blob, once finished, the result attribute contains an ArrayBuffer representing the file's data.
FileReader.readAsBinaryString()Starts reading the contents of the specified Blob, once finished, the result attribute contains the raw binary data from the file as a string.
FileReader.readAsDataURL()Starts reading the contents of the specified Blob, once finished, the result attribute contains a data: URL representing the file's data.
FileReader.readAsText()Starts reading the contents of the specified Blob, once finished, the result attribute contains the contents of the file as a text string.

所以只需要使用readAsDataURL()方法读取图片,绑定FileReader的onload事件,将读取的result中的url设置到img的src上

 

 1 <div><input id="upload" type="file"></div>
 2 <div><img id="pic" src=""></div>
 3 <script>
 4     var reader = new FileReader();
 5     reader.onload = function(e){
 6         document.getElementById('pic').setAttribute('src', e.target.result);
 7     };
 8     function readURL(input) {
 9         if (input.files && input.files[0]) {
10             reader.readAsDataURL(input.files[0]);
11         }
12     };
13     document.getElementById('upload').onchange = function(){
14         readURL(this);
15     };
16 </script>

 

转载于:https://www.cnblogs.com/zfy0098/p/5310506.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值