思路:通过h5+拍照或从手机选择图片,然后将图片压缩转成base64,通过post提交base64格式的图片字符串(这需要跟后台接口支持),上传成功之后,接口返回图片id,前端根据上传图片id,拼接img src下载图片展示。
项目用MUI开发app,界面如下:
现整理app头像上传和压缩代码示例:
1.部分html:
2.相关上传js:
//[头像]导航条点击事件处理
doc.querySelector('#headerPicSet').addEventListener('tap', function(e) {
//点击用户头像后,弹出actionSheet,选着从相册或是拍照;
if(mui.os.plus) {
var a = [{
title: "拍照"
}, {
title: "从手机相册选择"
}];
plus.nativeUI.actionSheet({
title: "上传用户头像",
cancel: "取消",
buttons: a
}, function(b) { /*actionSheet 按钮点击事件*/
switch(b.index) {
case 0:
break;
case 1: //拍照
getImage();
break;
case 2: //从手机相册选择
galleryImg();
break;
default:
break;
}
})
}
});
//拍照上传
function getImage() {
var c = plus.camera.getCamera(); //获取摄像头管理对象
c.captureImage(function(e) { //e为拍照成功的图片的路径
plus.io.resolveLocalFileSystemURL(e, function(entry) { //通过URL参数获取目录对象或文件对象
var s = entry.toLocalURL() + "?version=" + new Date().getTime();
uploadHeadBase64(s);
}, function(e) {
console.log("读取拍照文件错误:" + e.message);
});
}, function(s) {
console.log("error" + s);
}, {
filename: "_doc/head.png"
})
}
//本地相册选择图片上传
function galleryImg() {
plus.gallery.pick(function(a) {
plus.io.resolveLocalFileSystemURL(a, function(entry) {
plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
root.getFile("head.png", {}, function(file) {
//文件已存在
file.remove(function() {
console.log("file remove success");
entry.copyTo(root, 'head.png', function(e) {
uploadHeadBase64(e.fullPath + "?version=" + new Date().getTime());
},
function(e) {
console.log('copy image fail:' + e.message);
});
}, function() {
console.log("delete image fail:" + e.message);
});
}, function() {
//文件不存在
entry.copyTo(root, 'head.png', function(e) {
var path = e.fullPath + "?version=" + new Date().getTime();
uploadHeadBase64(path);
},
function(e) {
console.log('copy image fail:' + e.message);
});
});
}, function(e) {
console.log("get _www folder fail");
})
}, function(e) {
console.log("读取拍照文件错误:" + e.message);
});
}, function(a) {}, {
filter: "image"
})
}
//上传头像图片 uploadHeadBase64 6/2
function uploadHeadBase64(imgPath) {
var image = new Image();
image.src = imgPath;
image.onload = function() {
var imgData = getBase64Image(image);
console.log('上传baseIMG。。。')
console.log(imgData)
M.ajax({
type: 'post',
url: common.ajaxUrlPortal + '/front/cms/uploadImage/base64/head?Token=' + common.getToken(),
data: {
base64ImgData: imgData,
originalFilename:'head.jpeg'
},
dataType: 'json',
headers: {
Token: common.getToken()
},
success: function(data) {
console.log(typeof data);
console.log(JSON.stringify(data))
doc.getElementById('loginHeaderPic').src = common.ajaxUrlCms + '/image/download?id=' + data[0].id + '&fullPath=';
var page = plus.webview.getWebviewById('my_account_sub.html');
mui.fire(page, 'H_reload_getInfo', {});
},
error: function(xhr, type, errorThrown) {
M.toast('网络异常,请稍后再试!');
}
});
}
}
//将图片压缩转成base64
function getBase64Image(img) {
var canvas = document.createElement("canvas");
var width = img.width;
var height = img.height;
if(width > height) {
if(width > 750) {
height = Math.round(height *= 750 / width);
width = 750;
}
} else {
if(height > 750) {
width = Math.round(width *= 750 / height);
height = 750;
}
}
canvas.width = width;
/*设置新的图片的宽度*/
canvas.height = height;
/*设置新的图片的长度*/
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
/*绘图*/
var dataURL = canvas.toDataURL("image/jpeg", 0.3);
return dataURL.replace("data:image/jpeg;base64,", "");
}
==============================
下面是h5+上传图片:
//上传 5+ lhw 2017/4/7
function upload(imgPath) {
var image = new Image();
image.src = imgPath;
image.onload = function() {
var imgData = getBase64Image(image);
// 控制文件上传尺寸,目前初定为5M
if(imgData.length > 5 * 1024 * 1024) {
M.toast('文件过大,请选择其他头像!');
return;
}
plus.nativeUI.showWaiting('正在上传...');
var task = plus.uploader.createUpload(common.ajaxUrlPortal + '/front/cms/uploadImage/head?Token='+common.getToken(), {
method: "POST"
},
function(t, status) { //上传完成
if(Number(status) === 200) {
console.info(JSON.stringify(t));
//alert(JSON.stringify(t));
//alert("上传成功:"+t.responseText);
var obj = JSON.parse(t.responseText);
// wt.close(); //关闭等待提示按钮
plus.nativeUI.closeWaiting();
doc.getElementById('loginHeaderPic').src = common.ajaxUrlCms + '/image/download?id=' + obj[0].id + '&fullPath=';
var page = plus.webview.getWebviewById('my_account_sub.html');
mui.fire(page, 'H_reload_getInfo', {});
} else {
//alert("上传失败:"+status);
M.toast('上传失败!');
//wt.close();//关闭等待提示按钮
plus.nativeUI.closeWaiting();
}
}
);
//添加其他参数
task.addData("name", "pic");
task.addFile(imgPath, {
file: "pic"
});
task.start();
};
}
贴图postman测试图片上传接口: