<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>html5实战</title>
<style>
progress{}
#output{position: absolute; top: 100px; right: 100px; width: 400px; height: 300px; background: green;}
#drop{width: 200px; height: 150px; border:1px solid #000;}
</style>
<script>
window.οnlοad=function(){
var file = document.querySelector('#file-list');
var progress = document.querySelector('#progress');
var output = document.querySelector('#output');
var width= output.offsetWidth;
var height = output.offsetHeight;
//拖放文件事件
var drop = document.querySelector('#drop');
function dropHandle (event) {
event.preventDefault();
var info='';
var data=null;
var xhr=null;
if(event.type=='drop'){
var files = event.dataTransfer.files;
var len = files.length;
data = new FormData();
for(var i=0; i<len;i++){
data.append('file'+i,files[i]);
info+= files[i].name +'('+ files[i].size +'bytes'+')<br>'
}
xhr = new XMLHttpRequest();
xhr.open('post','http://www.baidu.com',true);
xhr.onreadystatechange=function(){
if(xhr.status==200 && xhr.readyState==4){
alert(xhr.responseText)
}
}
xhr.send();
}
drop.innerHTML = info;
}
drop.addEventListener('drop',dropHandle,false);
drop.addEventListener('dragenter',dropHandle,false);
drop.addEventListener('dragover',dropHandle,false);
file.addEventListener('change',function(event){
progress.value = 0;
var files = this.files;
//console.dir(files); // name size type lastModified
var imageType=/image.*/;
for(var i=0;i<files.length;i++){
var file = files[i];
var type = 'default';
var reader = new FileReader();
var blob = null;
if (imageType.test(file.type)) {
if(window.URL){
//这个可以取得图片地址
url = window.URL.createObjectURL(file)
}
reader.readAsDataURL(file);
type = 'image';
}else{
//只读部分内容 ,slice, mozSlice;
if(file.slice){
//0起始字节,5要读取字节数..JS里,一个字母为一字节,汉字为两字节
blob = file.slice(0,5);
}else if(file.mozSlice){
blob = file.mozSlice(0,5);
}else{
blob = file.webkitSlice(0,5);
}
reader.readAsText(blob);
// reader.readAsText(file);
type='text';
}
reader.οnprοgress=function(ev){
if (ev.lengthComputable) {
progress.value = 100*ev.loaded/ev.total;
}
}
reader.οnlοad=function(ev){
if (ev.lengthComputable) {
progress.value = 100*ev.loaded/ev.total;
}
var html='';
switch(type){
case 'image':
// URL 与 reader.result 作用一样,释放内存:window.URL.revokeObjectURL(url)
if(url){
alert(0)
html = '<img src='+url+' width="'+width+'" height="'+height+'"/>';
}else{
html = '<img src='+reader.result+' width="'+width+'" height="'+height+'"/>';
}
break;
case 'text':
html = reader.result;
break;
}
output.innerHTML = html;
}
reader.οnerrοr=function(){
output.innerHTML='could not read file, error code is '+ reader.error.code;
}
//console.dir(file);
}
},false)
}
</script>
</head>
<body>
<div id="container">
<input type="file" id="file-list" />
<progress id="progress" value ="1" max="100"></progress>
<div id="drop">把文件拖进这里</div>
</div>
<div id="output"></div>
</body>
</html>
html5 file
最新推荐文章于 2023-06-05 07:45:00 发布