选择的服务器获得密钥,WEB直传的方式好处就不必多说了,直接上代码吧
1、服务器koa框架
需要两个接口,一个是去阿里获取密钥的接口,一个是阿里回调的接口(接收OSS返回的数据)
先说第一个接口
user.js
const crypto = require("crypto");
const path = require("path");
let oss = {
OssAccessKeyId: "XXXXXXXX",
secret: "XXXXXXX",
host: "https://XXXXXXXXXl.oss-cn-hangzhou.aliyuncs.com"
};
// 获取上传oss身份证照片的密钥
async function getOssToken(ctx, next) {
try {
let client = new OSS(oss);
const dirPath = 'UserCardImg/'; // 这是我在OSS上面创建的文件名
let OssAccessKeyId = oss.OssAccessKeyId;
const secret = oss.secret;
const host = oss.host;
let end = new Date().getTime() + 360000;
let expiration = new Date(end).toISOString();
let policyString = {
expiration,
conditions: [
{ bucket: "XXXXX" },
["content-length-range", 0, 1048576000],
// ["starts-with", "$key", dirPath]
]
};
policyString = JSON.stringify(policyString);
const policy = Buffer.from(policyString).toString("base64");
let callbackString = {
callbackUrl: "http://XXXXX.com/api/user/getToken", // 此处就是接收OSS回调的接口地址
callbackBody: "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}",
callbackBodyType: "application/x-www-form-urlencoded"
};
callbackString = JSON.stringify(callbackString);
let callbackbody = Buffer.from(callbackString).toString("base64");
const signature = crypto
.createHmac("sha1", secret)
.update(policy)
.digest("base64");
ctx.body = {
code: 0,
OSSAccessKeyId: oss.OSSAccessKeyId
host,
policy,
signature,
callbackbody,
key: dirPath + end,
saveName: end,
startsWith: dirPath
};
} catch (e) {
console.log(e);
ctx.body = {
code: 1,
msg: '上传失败'
}
}
}
// 接收oss回调的接口
function getTokenCallback(ctx, next) {
let params = ctx.request.body;
try {
params['code'] = 0;
ctx.body = params;
} catch (e) {
console.log(e);
ctx.body = {
code: 1,
msg: '文件上传失败'
}
}
}
router.js
const Router = require('koa-router');
const App = require('../middleware/app');
const User = require('../controllers/user');
const Sever = require('../controllers/server');
module.exports = function () {
const router = new Router({
prefix: '/api'
});
router.get('/user/upload',User.getOssToken);
router.post('/user/getToken',User.getTokenCallback)
return router;
}
前端页面vue 我就只摘页面的部分代码了
总结自己此次踩过的坑:
1、后台host的地址忘了加https://,结果图片怎么也是上传不上去
2、OSS一定要设置允许跨域
3、我这个项目是vue打包放到iOS的客户端了,如果客户端不设置相机权限,选择拍照的时候APP闪退
4、前端上传图片的时候要以formdata的形式提交