公司为了节省流量费让前端直接上传上传七牛云服务起上,本人也是试了三种方法,踩了无数次坑,通过一天的努力,最终上传成功了。再次记录一下。
环境:uniapp + uView2.0
代码如下:
vue上传页面:
<!-- 上传图片 -->
<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) {
// 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
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, // 存到七牛云后的文件名字,访问图片会用到
'token': token, // uploadToken,需要动态获取,调用云函数接口获取
},
// 存成功后的回调
success: async (uploadFileRes) => {
let key = JSON.parse(uploadFileRes.data).key;
// 空间绑定的域名(在七牛云配置)+key就是文件的访问地址
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();
使用的依赖库有:"dateformat": "^3.0.3", "random-string": "^0.2.0",
网友评论