<text class="uploader-img-button" @tap="chooseTheImg">点击头像上传图片</text>
//选择图片
chooseTheImg() {
let that = this;
uni.chooseImage({
count: 1, //图片可选择数量
sizeType: ['compressed'], //original 原图,compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'], //album 从相册选图,camera 使用相机,默认二者都有。
extension: ['.png', '.jpg'], // 限制可选择的图片格式
success: res => {
// #ifdef MP-WEIXIN
that.uploadTheImg(res.tempFilePaths[0]);
// #endif
// #ifndef MP-WEIXIN
that.uploadTheImg(res.tempFiles[0]);
// #endif
}
});
},
//上传图片
uploadTheImg(file) {
let that = this;
uni.showLoading({
title: '上传中...',
mask: true
});
// 获取七牛上传信息接口(请求后端接口拿七牛的token)
GetQiniuUploadInfo({
FileType: 1,
FileName: file.name || new Date().getTime() + '.png',//没有名字用时间戳
})
.then(result => {
if (result.code == 100) {
uni.showLoading({
title: '上传中...',
mask: true
});
// #ifdef MP-WEIXIN
wx.uploadFile({
url: 'https://upload-z2.qiniup.com',
name: 'file',
filePath: file,
header: {
'Content-Type': 'multipart/form-data'
},
formData: {
key: result.data.fileName,
token: result.data.qnToken
},
success: function(res) {
uni.showToast({
title: '图片上传成功!'
});
},
fail: function(err) {
uni.showToast({
title: err
});
}
});
// #endif
// #ifndef MP-WEIXIN
// 七牛图片压缩(可跳过压缩)
qiniu
.compressImage(file, {
quality: file.size > 1000000 ? 0.8 : 1,
noCompressIfLarger: true
})
.then(data => {
// 压缩成功后上传图片
const observable = qiniu.upload(
data.dist,
result.data.fileName,
result.data.qnToken,
{
fname: file.name
},
{
useCdnDomain: true
}
);
observable.subscribe({
next(res) {},
error(err) {
uni.showToast({
title: err
});
},
complete(res) {
uni.showToast({
title: '图片上传成功!'
});
}
});
})
.catch(data => {
uni.showToast({
title: '上传失败'
});
});
// #endif
}
})
.catch(err => {
uni.showToast({
title: '上传失败'
});
});
}
扫码加q群