Js InputFile控件上传图片之前进行图片预览,使用For和event实现
在上传图片前能否实现图片预览
解决思路:
在上传控件浏览到文件后通过 onpropertychange 事件改变隐藏图片的路径,如果文件是图片格式,正常显示,否则提示格式不正确。
具体步骤:
1.先插入一个上传表单控件和一隐藏的空白图片。
<input type="file" id="upload">
<img id="pic" style="display:none">
2.在上传控件的属性改变(本例中为选择文件后),设置隐藏图片的地址为所选择的文件地址。
<script for="upload" event="onpropertychange">
pic.src=this.value
</script>
3.在隐藏图片加载完后显示。
<script for="pic" event="onload">
this.style.display="" //以行内元素方式显示隐藏的图片
</script>
4.如果所选择文件不是图片格式或者路径不正确,触发onerror事件,隐藏图片并弹出警告框。
<script for="pic" event="onerror">
//当 id 为 pic 的对象在装载过程中发生错误时触发此段代码
this.style.display="none" //隐藏图片
alert("所选文件并非图片,请重新选择")
</script>
5.完整代码。
<script for="upload" event="onpropertychange">
//当 id 为 upload 的对象上的属性发生变化时调用此段代码
//设置隐藏图片的地址为上传控件框的值
pic.src=this.value
</script>
<script for="pic" event="onload">
//当 id 为 pic 的对象在装载完成时触发此段代码
this.style.display="" //以行内元素方式显示隐藏的图片
</script>
<script for="pic" event="onerror">
//当 id 为 pic 的对象在装载过程中发生错误时触发此段代码
this.style.display="none" //隐藏图片
alert("所选文件并非图片,请重新选择")
</script>
<input type="file" id="upload">
<img id="pic" style="display:none">
技巧:显示对象除了设置display为空,还可以设为 inline 和 block
特别说明:
本例通过用 onpropertychange 捕获对象的属性变化事件,onload 捕获图片加载 完成后的事件,onerror 捕获图片加载时的出错事件,并通过script标签的for和event属性绑定到对象,而实现的上传图片预览效果。
1. onpropertychange 当在对象上发生对象上发生属性更改时触发。
2. onload 在浏览器完成对象的装载后立即触发。
3. onerror 当对象装载过程中发生错误时触发。
4. event 设置或获取脚本编写用于的事件。
5. for 设置绑定到事件脚本的对象,再获取脚本所绑定到的对象是用 htmlFor 。
转自:http://blog.chinaunix.net/u1/41559/showart_1901488.html
分享到:
相关推荐
input file上传图片预览
js获取input file控件选择的图片 并且立即在img标签显示出来
jsp实现input标签 file类型的上传图片即时预览功能
C#如何使用input[type=file]进行多个图片上传(XMLHttpRequest与后台交互) 详情可看:https://blog.csdn.net/weixin_44713389/article/details/90746459
上传控件input type='file' css 样式美化
js input file多个文件上传功能是一款可input上传图片和input file多个文件上传功能特效代码
NULL 博文链接:https://xace.iteye.com/blog/713126
主要介绍了javascript实现input file上传图片预览效果,感兴趣的小伙伴们可以参考一下
type=file选择图片后,在页面预览显示出来
input file上传图片预览其实很简单。今天小编就通过本文给大家介绍input file上传 图片预览功能的实现代码,比较简单,对input file 上传预览功能感兴趣的朋友参考下吧
用js实现input file选择图片然后预览功能,适用多种浏览器
HTML的文件上传控件的样式很不好的,我自己在网上找到的资料整合给大家。
这个案例是 html5的input file控件将文件上传到后台。
需要一个用户上传头像预览的功能,因此写了一段上传图片预览JS脚本,Input file图片预览的实现,需要的朋友可以看看
CSS自定义inputfile
window.createObjectURL 上传图片,实现web预览
//多张图片上传multiple <input type="file" id="file" multiple> //原生提交按钮 <input type="submit"> javascript <script> // 定义一个接收转为base64图片的数组 let ArrayImg=[] var index = 0;...
js input上传文件可input上传图片 js input上传文件可input上传图片
input type=file 调取手机照相机和选择照片上传 附件下载demo导入运行即可