一、獲取服務器通行證(即獲取AccessKey和accessKeySecret)
getAccess () { let that = this let url = '服務器地址' let params = { type: 'K' } // 第一步:獲取AccessKey this.$api.send(url, params).then((response) => { if (response.status === 200) { that.accessKey = response.body.data.data.Credentials /* global OSS */ that.client = new OSS.Wrapper({ region: 'oss-cn-shenzhen', bucket: '阿里雲bucket文件夾名', accessKeyId: that.accessKey.AccessKeyId, accessKeySecret: that.accessKey.AccessKeySecret, stsToken: that.accessKey.SecurityToken }) that.folder = response.body.data.data.folder; for (let i = 0; i < that.allList.length; i++) { if (!that.allList[i].hasUpload) {//allList 需要上傳的圖片數組
(function () { that.uploadItem(that.allList[i], i) })(i) } } } }) }
二、上傳到服務器
uploadItem (file, index) { let that = this let progress = function (p) { return function (done) { done() } } // 命名規則:web+id+10位時間戳+隨機4位數 let storeAs = 'web' + that.$user.getAll().userId + Math.round(new Date().getTime() / 1000) + Math.ceil(Math.random() * 100000).toString() + '.' + file.name.split('.')[1] // 第二步:調用阿里雲上傳函數上傳文件 this.client.multipartUpload(this.folder + '/' + storeAs, file.obj, { progress: progress }).then(function (result) { alert(上傳成功) }).catch(function (err) { console.log(err) }) }
this.getUnloadImg()