使用对象URL实现本地预览图片

来源:互联网 发布:开源的网管软件 编辑:程序博客网 时间:2024/05/20 18:01

今天测试《javascript高级程序》对象URL这一节的代码,大概是版本更新了,书上代码有一些需要调整的地方。

使用对象URL的好处为,不必将文件内容读到javascript中,而直接地可以使用文件内容。


html代码如下:

<form action="#"><input type="file" id="fileInput"></form><div id="imgShow"></div>



js代码如下:

var fileInput = document.getElementById('fileInput')fileInput.addEventListener('change',function(event){var imgShow = document.getElementById('imgShow'),files = this.files,    //原书这里是event.files,经过测试,修正为this.filesurl = window.URL.createObjectURL(files[0])    //创建URL对象if (url) {if (/image/.test(files[0].type)) {    //如果上传的文件类型为imageimgShow.innerHTML = '<img src="'+url+'">'    //将图片直接插入到页面中}else{imgShow.innerHTML = "not an image"}}else{imgShow.innerHTML = 'your browser doesnt support obj urls!'}})