JavaScript文件上传的常见问题整理
文件上传:<input type="file" /> (IE9及以下不支持下面这些功能,其它浏览器最新版本均已支持。)
1、允许上传文件数量
允许选择多个文件:
<input type="file" multiple>
只允许上传一个文件:
<input type="file" single>
2、上传指定的文件格式
<input type="file" accept="image/gif,image/png" />
这里的上传格式仅指打开上传弹窗选择文件时默认的文件格式,可手动修改成其它文件格式。
如果不限制上传图片的格式可写成:accept="imagei, p = document.getElementById('Preview'); var ul = document.getElementById('Errors'); for(var i = 0, f; f = files[i]; i++) { if(!f.type.match(ireg)) { //设置错误信息 var li = document.createElement('li'); li.innerHTML = '<li>' + f.name +'不是图片文件.</li>'; ul.appendChild(li); continue; } var reader = new FileReader(); reader.onload = (function(file) { return function(e) { var span = document.createElement('span'); var img = new Image; img.alt=file.name; img.onload = function() { console.log(img.height); // image is loaded; sizes are available }; img.class="lazy" data-src=this.result; span.innerHTML = '<img class="thumb" class="lazy" data-src="'+ this.result +'" alt="'+ file.name +'" />'; p.insertBefore(span, null); }; })(f); //读取文件内容 reader.readAsDataURL(f); } } if(window.File && window.FileList && window.FileReader && window.Blob) { document.getElementById('Files').addEventListener('change', fileSelect, false); } else { document.write('您的浏览器不支持File Api'); } </script> </body> </html>
上传txt文件内容预览(需对<>&'"|等符号进行过滤否则会中断读取):
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
body{margin:0;padding:0;}
img{vertical-align:bottom;}
</style>
</head>
<body>
<input type="file" multiple id="Files">
<div id="Preview"></div>
<ul id="Errors"></ul>
<script>
function encodeHTML(source) {
//return source;
return source
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\"/g, '"');
};
function fileSelect(e) {
e = e || window.event;
var files = e.target.files; //FileList Objects
var ireg = /text\/.*/i,
p = document.getElementById('Preview');
var ul = document.getElementById('Errors');
for(var i = 0, f; f = files[i]; i++) {
console.log(f.type);
if(!f.type.match(ireg)) {
//设置错误信息
var li = document.createElement('li');
li.innerHTML = '<li>' + f.name +'不是文本文件.</li>';
ul.appendChild(li);
continue;
}
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
var div = document.createElement('div');
div.className = "text"
div.innerHTML = encodeHTML(this.result);
p.insertBefore(div, null);
};
})(f);
//读取文件内容
reader.readAsText(f);
}
}
if(window.File && window.FileList && window.FileReader && window.Blob) {
document.getElementById('Files').addEventListener('change', fileSelect, false);
} else {
document.write('您的浏览器不支持File Api');
}
</script>
</body>
</html>
读取上传txt指定区域文本内容:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
body{margin:0;padding:0;}
img{vertical-align:bottom;}
</style>
</head>
<body>
<input type="file" multiple id="Files">
<button type="button" id="buttons" data-start="0" data-end="3">确定</button>
<div id="range"></div>
<div id="content"></div>
<script>
function readBlob(start, end) {
var files = document.getElementById('Files').files;
if(!files.length) {
alert('请选择文件');
return false;
}
var file = files[0],
start = parseInt(start, 10) || 0,
end = parseInt(end, 10) || (file.size - 1);
var r = document.getElementById('range'),
c = document.getElementById('content');
var reader = new FileReader();
reader.onloadend = function(e) {
if(this.readyState == FileReader.DONE) {
c.textContent = this.result;
r.textContent = "Read bytes: " + (start + 1) + " - " + (end + 1) + " of " + file.size + " bytes";
}
};
var blob;
blob = file.slice(start, end + 1, 'text/plain;charset=UTF-8');
reader.readAsBinaryString(blob);
};
try {
document.getElementById('buttons').addEventListener('click', function(e) {
if(e.target.tagName.toLowerCase() == 'button') {
var start = e.target.getAttribute('data-start'),
end = e.target.getAttribute('data-end');
readBlob(start, end);
}
});
} catch(ex) {
alert('something error happens!')
}
</script>
</body>
</html>
File接口提供了slice方法支持把文件切成不同的片段,第一个参数是起始的字节数,第二个参数是结束的字节数,还有一个可选的内容类型字符串可以作为第三个参数。早期的chrome和firefox版本不支持file.slice 可使用file.webkitSlice和file.mozSlice替代,最新版本均支持file.slice。
6、文件读取进度
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form>
<fieldset>
<legend>分度读取文件:</legend>
<input type="file" id="File" />
<input type="button" value="中断" id="Abort" />
<p>
<label>读取进度:</label><progress id="Progress" value="0" max="100"></progress>
</p>
<p id="Status"></p>
</fieldset>
</form>
<script>
var h = {
init: function() {
var me = this;
document.getElementById('File').onchange = me.fileHandler;
document.getElementById('Abort').onclick = me.abortHandler;
me.status = document.getElementById('Status');
me.progress = document.getElementById('Progress');
me.percent = document.getElementById('Percent');
me.loaded = 0;
//每次读取1M
me.step = 1024 * 1024;
me.times = 0;
},
fileHandler: function(e) {
var me = h;
var file = me.file = this.files[0];
var reader = me.reader = new FileReader();
//
me.total = file.size;
reader.onloadstart = me.onLoadStart;
reader.onprogress = me.onProgress;
reader.onabort = me.onAbort;
reader.onerror = me.onerror;
reader.onload = me.onLoad;
reader.onloadend = me.onLoadEnd;
//读取第一块
me.readBlob(file, 0);
},
onLoadStart: function() {
var me = h;
},
onProgress: function(e) {
var me = h;
me.loaded += e.loaded;
//更新进度条
me.progress.value = (me.loaded / me.total) * 100;
},
onAbort: function() {
var me = h;
},
onError: function() {
var me = h;
},
onLoad: function() {
var me = h;
if(me.loaded < me.total) {
me.readBlob(me.loaded);
} else {
me.loaded = me.total;
}
},
onLoadEnd: function() {
var me = h;
},
readBlob: function(start) {
var me = h;
var blob,
file = me.file;
me.times += 1;
if(file.slice) {
blob = file.slice(start, start + me.step + 1);
} else if(file.mozSlice) {
blob = file.mozSlice(start, start + me.step + 1);
}
me.reader.readAsText(blob);
},
abortHandler: function() {
var me = h;
if(me.reader) {
me.reader.abort();
}
}
};
h.init();
</script>
</body>
</html>
本文代码以chrome测试为主。
到此这篇关于JavaScript文件上传问题整理的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。