想做一个图片上传预览的功能。查了一下,看到两种思路,一个是上传到服务器,然后获取服务器资源,然后预览。一个是利用HTML5的FileReader。重点研究一下后者。

FileReader包含四个方法,分别是readAsBinaryString,readAsText,readAsDataURL和abort。通过字面意思都可以理解每个函数大概是什么功能,图片预览需要用到readAsDataURL。

先看代码

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <input type='file' id='file'/>
    <img src='' id='result'>
</body>
<script type="text/javascript">
    var file = document.getElementById('file');
    file.addEventListener('change',function(){
        var reader = new FileReader();
        reader.readAsDataURL(this.files[0]);
        reader.onload=function(){
            document.getElementById('result').src=this.result;
        }
    })
</script>
</html>

非常简单,FileReader一共支持6种事件,onabort(中断),onerror(出错),onloadstart(开始),onprogress(正在读取),onload(读取成功),onloadend(读取完毕)。这里用的读取成功。图片加载后,看一下图片src,发现是一个base64的数据,这个就和webpack缓存图片是一个方法。

用户上传的文件不一定是图片,还需要做一个文件类型的检查,网上的一段代码是这样的 if(!/image\/\w+/.test(file.type)),大概意思就是文件类型必须是image/*这种类型。那文件类型都有哪些可选值呢,测试后的结果如下

.png image/png
.git image/gif
.jpg image/jpeg
.doc application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.pdf application/pdf
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xls application/vnd.ms-excel

可以看出来file.type就是ContentType。除了type,file还有哪些属性呢

lastModified:上次修改的时间戳

lastModifiedDate:上次修改的日期

name:文件名

size:文件大小

type:文件类型

 

 

posted on 2017-02-22 23:20  lichliu  阅读(209)  评论(0编辑  收藏  举报