1. 引入aliyun-oss-sdk.min.js
<script type="text/javascript" src="/static/js/common/aliyun-oss-sdk.min.js"></script>
2. 通过后端接口获取临时访问权限生成OSS对象
var client = new OSS({ endpoint: 'oss-cn-beijing.aliyuncs.com', accessKeyId: '<Your AccessKeyId>', accessKeySecret: '<Your AccessKeySecret>', stsToken: '<Your SecurityToken>', bucket: 'Your bucket name' });
3. 上传文件
$('input').bind('change', function(e) { if (e.target.files && e.target.files.length > 0) { let file = e.target.files[0] var URL = window.URL || window.webkitURL; var imgURL = URL.createObjectURL(file); try { var reader = new FileReader(); reader.onload = (function (file) { return function (e) {
store.put(file.name, dataURItoBlob(result)).then(function () {
let url = store.signatureUrl(file.name); // 获取上传后的文件地址
}).catch(function (err) {
console.log(err)
});
}; })(e.target.files[0]); reader.readAsDataURL(e.target.files[0]) } catch (e) { console.log(e) } } })
// 转换成二进制
function dataURItoBlob(dataURI) {
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // mime类型
var byteString = atob(dataURI.split(',')[1]); //base64 解码
var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
var intArray = new Uint8Array(arrayBuffer); //创建视图
for (var i = 0; i < byteString.length; i++) {
intArray[i] = byteString.charCodeAt(i);
}
return new Blob([intArray], {type: mimeString});
}