前段时间公司要求做一个客户端图片直传oos的功能,要做到拍照和相册上传,要满足ios和Android端。作为一个刚入门vue和mui的前端菜鸟,在度娘上找了很久资源,终于捣鼓出来了。还是记录一份,方便查阅。
1、在oos上申请注册一个账号,得到对应的OSSAccessKeyId、AccessKeySecret等
2、准备工作好了之后就可以开始用到自己的项目中了
html部分只需要留一个img用于展现图片和一个点击事件就好
```
```
js部分
```
var server = "http://lctx.oss-cn-beijing.aliyuncs.com/"; //申请到的阿里云OSS地址
var OSSAccessKeyId= "LTAIC0Yv1Jbu5x7v"; //申请到的阿里云AccessKeyId和AccessKeySecret
var AccessKeySecret= "1OSGmCsAhh6Dwe9ZRQzc54wIDZskdk";//需要用自己申请的进行替换
var fname = ""; //表示文件名,例如 XXXX.jpg;
var dir ="uploads/headimg/"; //指定上传目录,此处指定上传到app目录下
var upImgPath = '';//上传图片名称存储
$('#headimage').on('tap',function(){//点击头像后的处理函数
showActionSheet();
})
function showImgDetail (src) {
$('#headimage').attr('src',src)
}
function plusReady() {
//Android返回键监听事件
plus.key.addEventListener('backbutton',function(){
myclose();
},false);
}
if (window.plus) {
plusReady();
} else {
document.addEventListener('plusready', plusReady, false);
}
var divid = 1;
var files = [];
//选取图片的来源,拍照和相册
function showActionSheet(conf){
var divid = 1;
var actionbuttons=[{title:"拍照"},{title:"相册选取"}];
var actionstyle={title:"选择照片",cancel:"取消",buttons:actionbuttons};
plus.nativeUI.actionSheet(actionstyle, function(e){
if(e.index==1){
getImage(divid);
}else if(e.index==2){
galleryImg(divid);
}
});
}
//相册选取图片
function galleryImg() {
plus.gallery.pick( function(p){
plus.io.resolveLocalFileSystemURL(p, function(entry) {
compressImage(entry.toLocalURL(),entry.name); //压缩图片
}, function(e) {
plus.nativeUI.toast("读取相册文件错误:" + e.message);
});
}, function ( e ) {
}, {
filename: "_doc/camera/",
filter:"image"
});
}
// 拍照
function getImage() {
var cmr = plus.camera.getCamera();
cmr.captureImage(function(p) {
plus.io.resolveLocalFileSystemURL(p, function(entry) {
compressImage(entry.toLocalURL(),entry.name);
}, function(e) {
plus.nativeUI.toast("读取拍照文件错误:" + e.message);
});
}, function(e) {
}, {
filename: "_doc/camera/",
index: 1
});
}
index = 1;
function appendFile(p) {
// files = [];
files.push({
name: "uploadkey"+ index,//+ index,//这个值服务器会用到,作为file的key
path: p
});
index++;
}
var suffix1 ;//获取文件后缀名
var myDate ;//获取当前时间
var keyname ;//路径及文件名
var pic_path ;
var my_filename = '' ;
//压缩图片
function compressImage(url,filename){
pic_path = url ;
my_filename = filename;
name="_doc/upload/"+divid+filename;//_doc/upload/F_ZDDZZ-1467602809090.jpg
fname = filename;
suffix1 = get_suffix(fname); //文件后缀 例如 .jpg
myDate = Math.round(new Date().getTime()/1000).toString();
plus.zip.compressImage({
quality:10,//quality: (Number 类型 )压缩图片的质量.取值范围为1-100
src:url,//src: (String 类型 )压缩转换原始图片的路径
dst:name,//压缩转换目标图片的路径
overwrite:true//overwrite: (Boolean 类型 )覆盖生成新文件 ,
},
function(event) {
var path = name;//压缩转换目标图片的路径
keyname =dir + my_uid+'_' + myDate + suffix1;
upImgPath = my_uid+'_' + myDate + suffix1;
saveimage(event.target,filename,path);
},function(error) {
plus.nativeUI.toast("压缩图片失败,请稍候再试");
});
}
//保存图片处理
function saveimage(url,name,path){
console.log(path)
appendFile(path);
var state=0;
var wt = plus.nativeUI.showWaiting("加载中...");
namename=name.substring(0,name.indexOf("."));//图片名称:1467602809090
var itemname="img-"+divid;//429img-F_ZDDZ
var itemvalue=plus.storage.getItem(itemname);
if(itemvalue==null){
itemvalue="{"+name+","+path+","+url+"}";//{IMG_20160704_112614,_doc/upload/F_ZDDZZ-IMG_20160704_112614.jpg,file:///storage/emulated/0/Android/data/io.dcloud...../doc/upload/F_ZDDZZ-1467602809090.jpg}
}else{
itemvalueitemvalue=itemvalue+"{"+name+","+path+","+url+"}";
}
plus.storage.setItem(itemname, itemvalue);
upload(url);
wt.close();
}
// 阿里云参数设置,用于计算签名signature
var policyText = {
"expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了
"conditions": [
["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
]
};
var policyBase64 = Base64.encode(JSON.stringify(policyText));
var message = policyBase64;
var bytes = Crypto.HMAC(Crypto.SHA1, message, AccessKeySecret, {
asBytes: true
});
var signature = Crypto.util.bytesToBase64(bytes);
// 上传文件
function upload(data_headimg) {
// var wt = plus.nativeUI.showWaiting();
var wt = plus.nativeUI.showWaiting("加载中...");
var task = plus.uploader.createUpload(server, {
method: "POST"
},
function(t, status) { //上传完成
console.log("t" + JSON.stringify(t));
console.log("status " + status);
if(status == 200) {
uploadPath(function(data){
wt.close();
if(data == 'ok'){
console.log("上传成功:" + t.responseText);
localStorage.setItem('my_headimg',data_headimg);
showImgDetail(data_headimg);
mui.toast('上传成功');
}
else{
mui.toast('上传失败');
}
})
//插入本地数据库
} else {
// outLine("上传失败:" + status);
wt.close();
}
}
);
//按照之前说明的参数类型,按顺序添加参数
task.addData("key", keyname);
task.addData("policy", policyBase64);
task.addData("OSSAccessKeyId", OSSAccessKeyId);
task.addData("success_action_status", "200");
task.addData("signature", signature);
console.log("files[0]" + JSON.stringify(files[0]));
for (var i = 0; i < files.length; i++) {
var f = files[i];
console.log("准备上传的图片路径:"+f.path);
console.log("准备上传的图片name:"+f.name);
task.addFile(f.path, {
key: "file",
name: "file",
mime: "image/jpeg"
});
}
task.start();
}
//得到文件名的后缀
function get_suffix(filename) {
var pos = filename.lastIndexOf('.');
var suffix = '';
if(pos != -1) {
suffix = filename.substring(pos)
}
return suffix;
}
function uploadPath(callback){
var getUrl = url + 'api/user/head1';
var my_uid = parseInt( localStorage.getItem('uid'));
var data = {
uid:my_uid,
head:upImgPath
}
postDate(getUrl,data,'POST',function(data){
if(data.code == 200){
callback('ok');
}
})
}