/**
* 单利模式,上传工具
*/
;
var uploadp = (function() {
var instance = null;
function getInstance(options) {
if(instance == null) {
instance = new myobj(options);
console.log("new instance");
return instance;
} else {
return instance;
}
}
function myobj(options) {
this.serverPath = "服务器路径";
this.fileList = options.fileList;
this.params = {}; //参数
}
var proto = myobj.prototype;
proto.before = function() {
var self = this;
var serverUrl = zlapp.serverPath() + "/UploadAllServlet?i=" + Math.random();
zlapp.ajax(serverUrl, {}, function(data) {
var param = {
key: "123.png",
policy: data.policy,
OSSAccessKeyId: data.accessid,
success_action_status: "200",
signature: data.signature
};
self.params = param;
}, "", {
async: false
})
}
proto.upload = function() {
var self = this;
self.before();
var formData = new FormData();
var key = "";
var filename = self.fileList[0];
var suffix = filename.substring(filename.lastIndexOf("."), filename.length);
filename = "picture/" + self.getDate() + "/" + self.getTimestamp() + suffix;
self.params.key = filename;
alert(JSON.stringify(self.params));
for(key in self.params) {
var paramValue = self.params[key];
formData.append(key, paramValue);
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(e) {
if(xhr.readyState == "4" && this.status == 200) { //上传成功
console.log(self.serverPath + "/" + filename);
mui.toast("上传成功");
// 图片预览
} else {
//mui.toast("上传失败");
}
}
//进度监听
xhr.upload.addEventListener("progress", function(evt) {
if(evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById("upload111").innerText = percentComplete.toString() + '%';
} else {
mui.toast("unable to compute");
}
}, false);
xhr.open('POST', this.serverPath);
formData.append("file", self.fileList[0]);
xhr.send(formData);
};
proto.getDate = function(htm) {
var myDate = new Date();
var year = myDate.getFullYear();
var month = Number(myDate.getMonth()) + 1;
month = month < 10 ? ("0" + month) : month;
return year + "-" + month;
};
proto.getTimestamp = function() {
return new Date().getTime();
};
return getInstance;
})();
/****************************************
如何使用
new uploadp({
fileList: files
}).upload();
****************************************/
1 个回复
1***@qq.com