項目中遇到利用阿里OSS上傳文件,線上很多示例用到了各種SDK,卻沒有看到OSS BrowserJS-SDK相關示例,鑒於腦子不好使,記一下。
封裝upload相關組件

使用npm安裝SDK的開發包
npm install ali-oss
在組件中實例化SDK並使用

上述四個參數可通過調用后台接口獲取,若前端直接封裝,容易暴露。前往(控制台-對象存儲OSS-基本設置)配置CORS

(詳見官方文檔)methods中封裝相關上傳方法
export default { name:'aliUpload', data () { return { videoName:'', videoUrl: '', size:'' } }, methods:{ doUpload(event){ this.$emit('getProgress',0) let file = event.target.files this.size = file[0].size let tmpArr = file[0].name.split('.') let tmpName = md5(Date.now() + tmpArr[0]) tmpName = tmpName + '.' + tmpArr[1] this.multipartUpload(tmpName,file[0]) }, multipartUpload(upName,upFile){ //Vue中封裝的分片上傳方法(詳見官方文檔) let _this = this const progress = async function (p) { //項目中需獲取進度條,故調用進度回調函數(詳見官方文檔) _this.$emit('getProgress',Math.round(p*100)) } try { let result = client.multipartUpload(upName,upFile, { progress, meta: { year: 2017, people: 'test' } }).then(res=>{ _this.videoUrl = res.res.requestUrls[0].split('?')[0] let info = {} info.name = res.name info.size = _this.size info.videoUrl = _this.videoUrl _this.$emit('getUrl',info) let head = client.head(upName); }).catch(err=>{ console.log(err) }); } catch (e) { // 捕獲超時異常 if (e.code === 'ConnectionTimeoutError') { console.log("Woops,超時啦!"); } console.log(e) } }, } }
外部引入組件使用