<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>HTML文件操作(读取)</title>
</head>
<body>
1.FileList一个文件集合 当在input中添加multiple就支持多文件上传
2.Blob是一个原始数据对象,它提供了slice方法可以读取原始数据中的某块数据。另外有两个属性:size(数据的大小),type(数据的MIME类型)
3.File对象继承自Blob对象,指向一个具体的文件,它还有两个属性:name(文件名), lastModifiedDate(最后修改时间)
4.FileReader对象设计用来读取文件里面的数据,提供三个常用的读取文件数据的方法,另外读取文件数据使用了异步的方式,非常高效
5.readAsBinaryString(Blob blob);传入一个Blob对象,然后读取数据的结果作为二进制字符串的形式放到FileReader的result属性中。
6.readAsText(Blob blob, optional DOMString encoding);→第一个参数传入Blog对象,然后第二个参数传入编码格式,异步将数据读取成功后放到result属性中,读取的内容是普通的文本字符串的形式。
7.readAsDataURL(Blob blob);→传入一个Blob对象,读取内容可以做为URL属性,也就是说可以将一个图片的结果指向给一个img的src属性
<input type="file" multiple="multiple" name="fileDemo" id="fileDemo" />
<input type="button" value="上传" class="submit"/>
<div id="result"></div>
<script src="//libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script>
$(function(){
$('.submit').on('click',function(){
showDataByText();
});
function showDataByUrl(){
var resultFile=document.getElementById('fileDemo').files[0];
if ((/image\/\w+/.test(resultFile.type))) {
if (resultFile) {
var reader = new FileReader();
reader.readAsDataURL(resultFile);
reader.onload = function (e) {
var urlData = this.result;
console.log(urlData);
document.getElementById("result").innerHTML += "<img src='" + urlData + "' alt='" + resultFile.name + "' />";
};
}
}
}
function showDataByBinaryString(){
var resultFile=document.getElementById('fileDemo').files[0];
if ((/text\/\w+/.test(resultFile.type))) {
if (resultFile) {
var reader = new FileReader();
reader.readAsBinaryString(resultFile);
reader.onload = function(e) {
var binaryData = this.result;
document.getElementById("result").innerHTML += binaryData;
};
}
}
}
function showDataByText(){
var resultFile=document.getElementById('fileDemo').files[0];
if ((/text\/\w+/.test(resultFile.type))) {
if (resultFile) {
var reader = new FileReader();
reader.readAsText(resultFile,'gb2312');
reader.onload = function (e) {
var textData = this.result;
document.getElementById("result").innerHTML += textData;
};
}
}
}
})
</script>
</body>
</html>