1.開通阿里雲的oss服務這些這里就不多做介紹了
2.登入阿里雲的后台管理系統創建一個Bucket
3.在后台管理系統中進入訪問控制
4.點擊用戶管理->新建用戶->填寫相關信息,就生成了下圖3
5.點擊生成用戶右側的授權,添加如圖的授權策略
6.點擊角色管理->新建角色,然后創建了一個如下圖的H5ROULE角色
7.點擊右側授權,並選擇如下圖的授權策略
8.在vue組件中使用
<template> <div class="upload"> <div class="oss_file"> <input type="file" :id="id" @change="doUpload"/> <img :src="url" alt=""> </div> </div> </template> <script> export default { name: 'upload', data () { return { region: 'oss-cn-hangzhou',根據你買的那個區的做相應的更改 bucket: 'buket名稱', id: 'upload', percentage: 0, url:'', urls:[], getToken:{ sign:'', } } }, methods:{ doUpload () { const _this = this; const urls = []; _this.$post('請求后台接口獲取accessKeyId,accessKeySecret和臨時驗簽SecurityToken',_this.getToken).then((result) => { console.log(result); const client = new OSS.Wrapper({ region: _this.region, accessKeyId: result.accessKeyId, accessKeySecret:result.accessKeySecret, stsToken: result.SecurityToken, bucket: _this.bucket }) _this.percentage = 0; const files = document.getElementById(_this.id) if (files.files) { const fileLen = document.getElementById(_this.id).files let resultUpload = '' for (let i = 0; i < fileLen.length; i++) { const file = fileLen[i] // 隨機命名 let random_name = this.random_string(6) + '_' + new Date().getTime() + '.' + file.name.split('.').pop() // 上傳 client.multipartUpload(random_name, file, { progress: function* (percentage, cpt) { // 上傳進度 _this.percentage = percentage } }).then((results) => { // 上傳完成 const url = 'http://buket名稱.oss-cn-hangzhou.aliyuncs.com/'+ results.name; _this.$store.dispatch("changeUrl", _this.url); _this.url = url; console.log(url); }).catch((err) => { console.log(err) }) } } }) },
// 隨機生成文件名 random_string(len) { len = len || 32; var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; var maxPos = chars.length; var pwd = ''; for (let i = 0; i < len; i++) { pwd += chars.charAt(Math.floor(Math.random() * maxPos)); } return pwd; } }, watch:{ url(val){ if(val){ this.urls.push(val); } } } }
</script>
<style lang="less"> .oss_file { height: 150px; width: 150px; border-radius: 50%; // background: red; img{ width:100%; display: inline-block; float: right; } } .oss_file input { right: 0; top: 0; opacity: 0; filter: alpha(opacity=0); cursor: pointer; width: 100%; height: 100%; } </style>
9.后台操作如下以java為例