<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link href="css/mui.min.css" rel="stylesheet" />
</head>
<body>
<script src="js/mui.min.js"></script>
<img id="img" style="height: 100px;width: 100px;" />
<button id="upload" type="button" class="mui-btn mui-btn-blue mui-btn-block">上传图片</button>
<script type="text/javascript">
mui.init();
var imgpath;
document.getElementById('upload').addEventListener('tap',function(){
var btnArray = [{title:"拍照"},{title:"打开相册"}]; //选择按钮 1 2 3
plus.nativeUI.actionSheet( {
title:"请选择",
cancel:"取消", // 0
buttons:btnArray
},
function(e){
var index = e.index; //
// alert(index);
switch (index){
case 1:
//写自己的逻辑
takePhoto();
break;
case 2:
openphoto();
break;
}
} );
})
//拍照
function takePhoto(){
var imh;
var cmr = plus.camera.getCamera();
cmr.captureImage( function ( p ) {
//成功
plus.io.resolveLocalFileSystemURL( p, function ( entry ) {
var img_name = entry.name;//获得图片名称
imh = entry.toLocalURL();//获得图片路径
upload_img(imh);
}, function ( e ) {
console.log( "读取拍照文件错误:"+e.message );
} );
}, function ( e ) {
console.log( "失败:"+e.message );
}, {filename:'_doc/camera/',index:1} );
}
//打开相册
function openphoto(){
var imh;
plus.gallery.pick( function(path){
imh = path;//获得图片路径
upload_img(imh);
}, function ( e ) {
console.log( "取消选择图片" );
}, {filter:"image"} );
}
//初始上传地址
var server="http://192.168.1.4/Second_Hand/php/upload2.php"; // 学员测试使用
var files=[]; //图片存放的数组 可以上传一个,或者多个图片
//上传图片
function upload_img(p){
//又初始化了一下文件数组 为了支持我的单个上传,如果你要一次上传多个,就不要在写这一行了
//注意
files=[];
var n=p.substr(p.lastIndexOf('/')+1);
files.push({name:"uploadkey",path:p});
//开始上传
start_upload();
}
//开始上传
function start_upload(){
if(files.length<=0){
plus.nativeUI.alert("没有添加上传文件!");
return;
}
//原生的转圈等待框
var wt=plus.nativeUI.showWaiting();
var task=plus.uploader.createUpload(server,
{method:"POST"},
function(t,status){ //上传完成
alert("111",status);
if(status==200){
//资源
var responseText = t.responseText;
//转换成json
var json1 = eval('(' + responseText + ')');
//上传文件的信息
var files = json1.files;
//上传成功以后的保存路径
var img_url = files.uploadkey.url;
//ajax 写入数据库
alert('222',files)
//关闭转圈等待框
wt.close();
}else{
console.log("上传失败:"+status);
//关闭原生的转圈等待框
wt.close();
}
});
task.addData("client","");
task.addData("uid",getUid());
for(var i=0;i<files.length;i++){
var f=files[i];
task.addFile(f.path,{key:f.name});
}
task.start();
}
// 产生一个随机数
function getUid(){
return Math.floor(Math.random()*100000000+10000000).toString();
}
</script>
</body>
</html>
0 个回复