OSS文件浏览器直传方案
更新时间:
依赖准备
- 在云开发平台应用中设置如下环境变量
AKID=安全受限的 Access key ID
AKSK=Access key secret
REGION=OSS 所在的 Region
OSSBUCKET=Bucket 名称
OSSDIR=上传目录
OSS操作子账号授权策略
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": "oss:*",
"Resource": [
"acs:oss:*:*:你的OSS Bucket名称",
"acs:oss:*:*:你的OSS Bucket名称/*"
]
}
]
}
OSS设置跨域访问
打开自己的 OSS Bucket 概览页,在「基础设置」中找到「跨域访问」
点击「设置」,参考下图输入您自己允许跨域上传的域名,提交即可
NodeJS 版本
在云开发平台应用中创建 /api/osstoken.js
const crypto = require("crypto");
const config = {
dir: process.env['OSSDIR'], // 上传目录
bucket: process.env['OSSBUCKET'],// Bucket 名称
region: process.env['REGION'],// OSS 所在的 Region
accessKeyId: process.env['AKID'],// 安全受限的 Access key ID
accessKeySecret: process.env['AKSK'],// Access key secret
expAfter: 3600000, // 签名失效时间,毫秒
maxSize: 1048576000 // 文件最大尺寸
};
module.exports.handler = function(event, context, callback) {
var host = `https://${config.bucket}.oss-${config.region}.aliyuncs.com`;
var expireTime = new Date().getTime() + config.expAfter;
var expiration = new Date(expireTime).toISOString();
var policyString = JSON.stringify({
'expiration': expiration,
'conditions': [
['content-length-range', 0, config.maxSize],
['starts-with', '$key', config.dir]
]
});
var policy = Buffer.from(policyString).toString('base64');
var signature = crypto.createHmac('sha1', config.accessKeySecret).update(policy).digest("base64");
var tokenData = {
'signature': signature,
'policy': policy,
'host': host,
'accessid': config.accessKeyId,
'expire': expireTime,
'dir': config.dir
};
var responseObject = {
isBase64Encoded: true,
statusCode: 200,
headers: {
"Content-type": "application/json; charset=utf-8"
},
body: Buffer.from(JSON.stringify(tokenData)).toString("base64")
};
callback(null, responseObject);
};
Python 版本
在云开发平台应用中创建 /api/osstoken.py
# -*- coding: UTF-8 -*-
import os
import base64
import time
import datetime
import json
import hmac
from hashlib import sha1 as sha
access_key_id = os.environ['AKID']
access_key_secret = os.environ['AKSK']
host = 'http://{}.oss-{}.aliyuncs.com'.format(os.environ['OSSBUCKET'], os.environ['REGION'])
upload_dir = os.environ['OSSDIR']
expire_time = 3600 # 单位秒
def get_iso_8601(expire):
gmt = datetime.datetime.utcfromtimestamp(expire).isoformat()
gmt += 'Z'
return gmt
def get_token():
now = int(time.time())
expire_syncpoint = now + expire_time
expire = get_iso_8601(expire_syncpoint)
policy_dict = {}
policy_dict['expiration'] = expire
condition_array = []
array_item = []
array_item.append('starts-with')
array_item.append('$key')
array_item.append(upload_dir)
condition_array.append(array_item)
policy_dict['conditions'] = condition_array
policy = json.dumps(policy_dict).strip()
policy_encode = base64.b64encode(policy.encode())
h = hmac.new(access_key_secret.encode(), policy_encode, sha)
sign_result = base64.encodestring(h.digest()).strip()
token_dict = {}
token_dict['accessid'] = access_key_id
token_dict['host'] = host
token_dict['policy'] = policy_encode.decode()
token_dict['signature'] = sign_result.decode()
token_dict['expire'] = expire_syncpoint
token_dict['dir'] = upload_dir
result = json.dumps(token_dict)
return result
def handler(event, context):
token = get_token()
api_rep = {
"isBase64Encoded":"true",
"statusCode":"200",
"headers":{"Content-Type":"application/json; charset=utf-8"},
"body":str(base64.b64encode(token.encode("utf-8")),"utf-8")
}
return api_rep
PHP版本
在云开发平台应用中创建 /api/osstoken.php
<?php
function handler($event, $context) {
$config = array(
'dir' => getenv('OSSDIR'), // 上传目录
'bucket' => getenv('OSSBUCKET'),// Bucket 名称
'region' => getenv('REGION'),// OSS 所在的 Region
'accessKeyId' => getenv('AKID'),// 安全受限的 Access key ID
'accessKeySecret' => getenv('AKSK'),// Access key secret
'expAfter' => 3600, // 签名失效时间,秒
'maxSize' => 1048576000 // 文件最大尺寸
);
$host = 'https://' . $config['bucket'] . '.oss-' . $config['region'] . '.aliyuncs.com';
$now = strtotime('now');
$expireTime = $now + $config['expAfter'];
$expiration = gmdate('Y-m-d\TH:i:s\Z', $expireTime);
$policy = array(
"expiration" => $expiration,
"conditions" => array(
array("content-length-range", 0, $config['maxSize']),
array("starts-with", "\$key", $config['dir'])
)
);
$policyString = base64_encode(json_encode($policy));
$signature = base64_encode(hash_hmac('sha1', $policyString, $config['accessKeySecret'], true));
$tokenData = array(
"signature" => $signature,
"policy" => $policyString,
"host" => $host,
"accessid" => $config['accessKeyId'],
"expire" => $expireTime,
"dir" => $config['dir']
);
$responseObject = array(
"isBase64Encoded" => true,
"statusCode" => 200,
"headers" => array(
"Content-type" => "application/json; charset=utf-8"
),
"body" => base64_encode(json_encode($tokenData))
);
return $responseObject;
}
?>
浏览器端直传代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OSS浏览器直传文件方案</title>
</head>
<body>
<fieldset style="margin-top: 30px;border-color:#e6e6e6;border-width:1px 0 0;">
<legend style="margin-left:20px;padding:0 10px;font-size:20px;font-weight:300;">OSS浏览器直传文件方案</legend>
</fieldset>
<blockquote style="margin 10px 0 0;padding:10px;border-width:1px 1px 1px 5px;border-color:#e6e6e6;border-style:solid;">
请选择图片:
<input id="inputFile" name="inputFile" type="file" style="height:38px;line-height:38px;padding:0 18px;background:#1E9FFF;color:#fff;font-size:14px;border-radius:2px;" />
</blockquote>
<blockquote style="margin 10px 0 0;padding:10px;border-width:1px 1px 1px 5px;border-color:#e6e6e6;border-style:solid;">
预览图:
<div><image id="ossImage" src="" height="300"></image></div>
</blockquote>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#inputFile").on('change', function(file) {
console.log($("#inputFile").get(0).files[0]);
var file = $("#inputFile").get(0).files[0];
$.post('/api/osstoken').then(function (res) {
console.log(res);
var policy = res;
var filename = (new Date().getTime()) + '_' + file.name
var formData = new FormData();
formData.append('Filename', filename);
formData.append(
'key',
policy.dir + '/' + filename
);
formData.append('OSSAccessKeyId', policy.accessid);
formData.append('policy', policy.policy);
formData.append('Signature', policy.signature);
formData.append('success_action_status', '200');
formData.append('file', file);
$.ajax({
url: policy.host,
type: 'post',
processData: false,
contentType: false,
data: formData,
success: function (res) {
console.log(res);
var imageUrl = policy.host + '/' + policy.dir + '/' + filename;
console.log(imageUrl);
$("#ossImage").attr('src', imageUrl);
}
})
});
})
});
</script>
</body>
</html>
文档内容是否对您有帮助?