request.js配置
export const selectImg = async function(callback) {
let files;
let options = {};
let token = 'Bearer ' + uni.getStorageSync('token');
try {
files = await chooseImage(options);
console.log(files)
uni.uploadFile({
url:baseurl + '/common/upload',
filePath: files[0].path,
name: 'file',
header: {
Authorization: token
},
success: (uploadFileRes) => {
if (uploadFileRes.statusCode == 200) {
uni.showToast({
title: '上传成功!',
icon: 'none'
});
callback(uploadFileRes);
} else {
uni.showToast({
title: '网络错误,上传超时!',
icon: 'none'
});
}
},
fail: (res) => {},
});
} catch (err) {
console.log(err)
}
}
export const chooseImage = function(data) {
return new Promise((resolve, reject) => {
uni.chooseImage({
count: data.count || 1, //默认1
sizeType: 'compressed', //可以指定是原图还是压缩图,默认二者都有
sourceType: data.sourceType || ['camera', 'album'], //从相册选择
success: function(res) {
resolve(res.tempFiles);
},
fail: err => {
uni.hideLoading()
reject(err);
}
});
});
}
使用:
<view class="grid col-4 grid-square flex-sub">
<view class="bg-img" v-for="(item,index) in fjarr" :key="index" @tap="ViewImage":data-url="item.url">
<image mode="aspectFill" :src='item.url'></image>
<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
<text class='cuIcon-close'></text>
</view>
</view>
<view class="solids" @tap="ChooseImage" v-if="fjarr.length<1">
<text class='cuIcon-cameraadd'></text>
</view>
</view>
import { selectImg } from "@/common/request"
ChooseImage() {
selectImg((data) => {
let json = JSON.parse(data.data)
this.fjarr.push({
url: json.data,
keys: ''
})
})
},
ViewImage(e) {
let a = [e.currentTarget.dataset.url]
uni.previewImage({
urls: a,
current: e.currentTarget.dataset.url
});
},
DelImg(e) {
uni.showModal({
title: '提示',
content: '确定要删除图片吗?',
cancelText: '取消',
confirmText: '确定',
success: res => {
if (res.confirm) {
this.fjarr.splice(e.currentTarget.dataset.index, 1)
}
}
})
},