html 部分
javascript部分
// 选择图片预览
$("#container").on("change","#image_file",function(){
var oFile = document.getElementById('image_file').files[0];
var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
if (! rFilter.test(oFile.type)) {
$.toast("您应该只选择有效的图像文件!","cancel");
return;
}
var iMaxFilesize = 1048576; // 1MB
if (oFile.size > iMaxFilesize) {
$.toast("你的文件是非常大的。我们不能接受它。请选择更小的文件","cancel");
return;
}
var oImage = document.getElementById('preview');
// prepare HTML5 FileReader
var oReader = new FileReader();
oReader.onload = function(e){
oImage.src = e.target.result;
oImage.onload = function () {};
};
oReader.readAsDataURL(oFile);
});
// 上传图片
$("#container").on("click","#upFace",function(){
var vFD = new FormData(document.getElementById('upload_form'));//获取表单数据
var oXHR = new XMLHttpRequest();
oXHR.upload.addEventListener('progress', function(e){//上传进度
if(e.lengthComputable){
var iPercentComplete = Math.round(e.loaded * 100 / e.total);
$("#progress_percent").text(iPercentComplete.toString() + '%');
if (iPercentComplete == 100) {
$.toast("上次完成");$("#progress_percent").hide();
}
}
}, false);
oXHR.addEventListener('load', function(e){//完成后的事件
console.log(e.target.responseText);
}, false);
oXHR.addEventListener('error', function(e){//上次错误
$.toast("上载文件时发生错误","cancel");
}, false);
oXHR.addEventListener('abort', function(e){//取消上传
$.toast("上传已被用户或浏览器取消连接的连接","cancel");
}, false);
var phone = window.localStorage["phone"];
var token = window.localStorage["token"];
var uri = "http://192.168.1.83:8886/api/upload/face?phone="+phone+"&token="+token;
oXHR.open('POST', uri);
oXHR.send(vFD);
});
后台图片上传部分,用的beego
func (this *Upload) Face() {
phone := this.GetString("phone")
f, h, err := this.GetFile("image_file")
if err != nil {
this.Ctx.WriteString(err.Error())
return
}
f.Close()
path := "./static/uploader/face/"
tofile := path + phone + filepath.Ext(h.Filename)
err = this.SaveToFile("image_file", tofile)
if err != nil {
this.Ctx.WriteString(err.Error())
return
}
this.Ctx.WriteString(tofile)
}