1. 先进入APICloud 控制台,开启数据云2.0 。
2. 编写项目代码
a. 选择图片
可以使用api 对象的getPicture 方法,或者其他图片选择模块,如WXPhotoPicker。
function fngetPicture() {
api.getPicture({
sourceType: 'camera',
encodingType: 'jpg',
mediaValue: 'pic',
destinationType: 'url',
allowEdit: false,
quality: 100,
saveToPhotoAlbum: false
}, function(ret, err) {
if (ret) {
picURL = ret.data
} else {
console.log(JSON.stringify(err));
}
});
}
b. 计算数据云访问验证密钥
相关文档参考:数据云2.0
// 先计算appKey, 数据库访问需要身份验证。把在应用概览里看到的appid, appKey 填入,进行SHA1运算。
var now = Date.now();
var appKey = SHA1("A698059072xxxx" + "UZ" + "9CF6F8C5-235C-26EC-649B-88CA038Dxxxx" + "UZ" + now) + "." + now
c. 使用api.ajax 接口上传文件
function fnajaxpictofile() {
api.ajax({
url: 'https://d.apicloud.com/mcm/api/file',
method: 'POST',
headers: {
"X-APICloud-AppId": "A698059072xxxx", //填写自己的appid
"X-APICloud-AppKey": appKey
},
data: {
"values": {
"filename": "testPicName"
},
"files": {
"file": picURL,
}
}
}, function(ret, err) {
if (ret) {
alert(JSON.stringify(ret));
} else {
alert(JSON.stringify(err));
}
});
}
附完整代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
<title>title</title>
<link rel="stylesheet" type="text/css" href="../css/api.css" />
<style>
body {
padding: 60px;
}
button {
margin: 10px;
}
</style>
</head>
<body>
<button type="button" onclick="getPicture()" name="button">先获取一张本地图片</button>
<button type="button" onclick="fnajaxpictofile()" name="button">开始上传图片到file表</button>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/APICloud-rest-SHA1.js"></script>
<script type="text/javascript">
var picURL = "";
// 先计算appKey, 数据库访问需要身份验证。把在应用概览里看到的appid, appKey 填入,进行SHA1运算。
var now = Date.now();
var appKey = SHA1("A698059072xxxx" + "UZ" + "9CF6F8C5-235C-26EC-649B-88CA038Dxxxx" + "UZ" + now) + "." + now
function getPicture() {
api.getPicture({
sourceType: 'camera',
encodingType: 'jpg',
mediaValue: 'pic',
destinationType: 'url',
allowEdit: false,
quality: 100,
saveToPhotoAlbum: false
}, function(ret, err) {
if (ret) {
picURL = ret.data
} else {
alert(JSON.stringify(err));
}
});
}
//上传文件到file表
function fnajaxpictofile() {
api.ajax({
url: 'https://d.apicloud.com/mcm/api/file',
method: 'POST',
headers: {
"X-APICloud-AppId": "A698059072xxxx", //填写自己的appid
"X-APICloud-AppKey": appKey
},
data: {
"values": {
"filename": "testPicName"
},
"files": {
"file": picURL,
}
}
}, function(ret, err) {
if (ret) {
alert(JSON.stringify(ret));
} else {
alert(JSON.stringify(err));
}
});
}
</script>
</html>
需要引用的js APICloud-rest-SHA1.js