/*
*异步上传文件
*option参数
**url:上传路径
**data:上传的其他数据{id:"1"}
**maxSize:文件最大值(单位M)
**callback:回调函数(可空)
**beforeSend:上传前函数(可空)
*/
function Upload(option) {
var fd = new FormData(),
xhr = new XMLHttpRequest(),
input;
if (document.getElementById('_RobinUploadInput')) {
input = document.getElementById('_RobinUploadInput');
} else {
input = document.createElement('input');
input.setAttribute('id', '_RobinUploadInput');
input.setAttribute('type', 'file');
input.setAttribute('name', 'file');
document.body.appendChild(input);
input.style.display = 'none';
}
input.click();
input.onchange = function () {
if (!input.value) { return; }
if (option.maxSize && input.files[0].size > option.maxSize * 1024 * 1024) {
alert("请上传小于' + option.maxSize + 'M的文件");
return;
}
if (option.beforeSend instanceof Function) {
if (option.beforeSend(input) === false) {
return false;
}
}
if (option.data) {
for (var name in option.data) {
fd.append(name, option.data[name]);
}
}
fd.append('Filedata', input.files[0]);
xhr.open('post', option.url);
xhr.onreadystatechange = function () {
if (xhr.status == 200) {
if (xhr.readyState == 4) {
if (option.callback instanceof Function) {
option.callback(xhr.responseText);
}
}
} else {
alert("上传失败");
}
}
xhr.upload.onprogress = function (event) {
var pre = Math.floor(100 * event.loaded / event.total);
if (option.uploading instanceof Function) {
option.uploading(pre);
}
}
xhr.send(fd);
}
}