公司為了節(jié)省流量費(fèi)讓前端直接上傳上傳七牛云服務(wù)起上球恤,本人也是試了三種方法哀九,踩了無(wú)數(shù)次坑剿配,通過(guò)一天的努力,最終上傳成功了阅束。再次記錄一下惨篱。
環(huán)境:uniapp + uView2.0
代碼如下:
vue上傳頁(yè)面:
<!-- 上傳圖片 -->
<view style="transform: translateX(-10rpx);">
<u-upload
:fileList="fileList"
@afterRead="afterRead"
@delete="deletePic"
name="1"
multiple
:previewFullImage="true"
:maxCount="9"
></u-upload>
<u-line length="690rpx" color="#F6F6F6" margin="30rpx 0 33rpx 0"></u-line>
</view>
<script>
export default {
data() {
return {
fileList: [],
fileUrlList: [],
};
},
methods: {
// 刪除圖片
deletePic(event) {
this.fileList.splice(event.index, 1)
this.fileUrlList.splice(event.index, 1)
},
// 新增圖片
async afterRead(event) {
// 當(dāng)設(shè)置 multiple 為 true 時(shí), file 為數(shù)組格式,否則為對(duì)象格式
let lists = [].concat(event.file)
let fileListLen = this.fileList.length
lists.map((item) => {
this.fileList.push({
...item,
status: 'uploading',
message: '上傳中'
})
})
for (let i = 0; i < lists.length; i++) {
const result = this.$uploader.upload2qiniu(lists[i].url)
result.then(res=>{
this.fileUrlList.push(res.msg)
})
let item = this.fileList[fileListLen]
this.fileList.splice(fileListLen, 1, Object.assign(item, {
status: 'success',
message: '',
url: result
}))
fileListLen++
}
},
chooseLocation() {
let that = this;
uni.chooseLocation({
success: function(res) {
that.form.address = res.name;
that.form.latitude = res.latitude;
that.form.longitude = res.longitude;
},
fail(err) {
console.log(err)
}
});
},
}
};
</script>
主要的js文件
1.獲取上傳所用token需要后端人員提供接口 2.上傳完成需要后端提供圖片群路徑的接口
const dateFormat = require('dateformat');
var randomString = require('random-string');
class Uploader {
constructor() {
this.qiniuTokenApi = '獲取token的后端地址';
}
//七牛云上傳
async upload2qiniu(file) {
// 獲取token
let tokenData = await this.getToken();
let token = tokenData.msg
return new Promise((resolve, reject) => {
let customFileName = config.qiNiuSpaceName + "/" + dateFormat(new Date(), "yyyy/mm/dd/HH") + "/" + randomString({
length: 10
})
uni.uploadFile({
url: config.uploadQiNiuDomain,
filePath: file,
name: 'file',
formData: {
'key': customFileName, // 存到七牛云后的文件名字围俘,訪問(wèn)圖片會(huì)用到
'token': token, // uploadToken砸讳,需要?jiǎng)討B(tài)獲取,調(diào)用云函數(shù)接口獲取
},
// 存成功后的回調(diào)
success: async (uploadFileRes) => {
let key = JSON.parse(uploadFileRes.data).key;
// 空間綁定的域名(在七牛云配置)+key就是文件的訪問(wèn)地址
let url = await this.getUrl(JSON.parse(uploadFileRes.data).key);
resolve(url)
},
fail: (err) => {
console.log('上傳失敗了', err);
}
});
})
}
async getToken() {
return new Promise((resolve, reject) => {
uni.request({
url: this.qiniuTokenApi,
method: "GET",
success(res) {
resolve(res.data)
},
fail(err) {
reject(err)
}
})
})
}
async getUrl(key) {
let url = '上傳圖片之后獲取全路徑的url ' + '?key=' + key
return new Promise((resolve, reject) => {
uni.request({
url: url,
method: "GET",
success(res) {
resolve(res.data)
},
fail(err) {
reject(err)
}
})
})
}
}
export default new Uploader();
使用的依賴庫(kù)有:"dateformat": "^3.0.3", "random-string": "^0.2.0",