博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HTML5图片上传预览
阅读量:4670 次
发布时间:2019-06-09

本文共 2105 字,大约阅读时间需要 7 分钟。

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.onabort A handler for the abort event. This event is triggered each time the reading operation is aborted.
FileReader.onerror A handler for the error event. This event is triggered each time the reading operation encounter an error.
FileReader.onload A handler for the load event. This event is triggered each time the reading operation is successfully completed.
FileReader.onloadstart A handler for the loadstart event. This event is triggered each time the reading is starting.
FileReader.onloadend A handler for the loadend event. This event is triggered each time the reading operation is completed (either in success or failure).
FileReader.onprogress A 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 
2
3

 

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

你可能感兴趣的文章
如何成为合格的数据分析师
查看>>
ArcGIS10.5资源分享
查看>>
理解http幂等性
查看>>
grep运用
查看>>
logstash收集syslog日志
查看>>
jenkins修改数据存放路径
查看>>
poj2481树状数组解二维偏序
查看>>
软件工程网络15个人阅读作业1(201521123062 杨钧宇)
查看>>
根据控制点坐标对完成坐标转换
查看>>
Boost.ASIO简要分析-4 多线程
查看>>
java调用支付宝接口代码介绍
查看>>
安装apache 后,找不到服务,解决办法
查看>>
【洛谷 T47488】 D:希望 (点分治)
查看>>
spring-MVC访问静态资源
查看>>
JavaScript异步加载与同步加载
查看>>
Eclipse搭建springboot项目(六)全局异常
查看>>
Android 报错:error: too many padding sections on bottom border
查看>>
IOS开发 ios7适配
查看>>
1806. [NOIP2014]无线网路发射器选址
查看>>
根据指定的commit查找对应的log
查看>>