图片选择,图片上传,点击查看,点击删除。
uniapp自带的chooseImage和uploadFile就可以解决选择和上传。预览/查看用previewImage,删除就直接移除list里面的项就好了。
template部分
<view class="order-up">
<view class="camera" @tap="ChooseImage">
<text class="iconfont icon-shangchuantupian"></text>
<text class="text">上传凭证</text>
</view>
<view class="img" v-for="(item, i) in imgList" :key='i' @click="ViewImage(i)">
<image style="width: 100%;height: 100%;" :src="item"></image>
<view @click.stop="DelImg(i)" style="display: inline;">
<text class="iconfont close icon-guanbi"></text>
</view>
</view>
</view>
js
data() {
return {
imgList: [],
}
},
methods: {
ChooseImage() {
uni.chooseImage({
success: (res) => {
console.log(res)
//判断图片格式
let tempStr = res.tempFilePaths[0].split('.');
let lowerStr = tempStr[1].toLowerCase();
console.log(lowerStr)
if (lowerStr != 'png' && lowerStr !== 'jpg' && lowerStr !== 'jpeg') {
uni.showToast({
title: '请上传PNG、JPG、JPEG格式的图片',
icon: 'none',
duration: 3000
});
return;
}
let images = res.tempFilePaths;
for (const path of images) {
//上传到后端,写了一个util.js
util.uploadFile('upload/upload', path)
.then((srcPath) => {
this.imgList.push(srcPath.url)
})
}
}
})
},
ViewImage(i) {
let imgurl = []
this.imgList.forEach(item => imgurl.push(item))
uni.previewImage({
urls: imgurl,
current: this.imgList[i]
});
},
DelImg(i) {
uni.showModal({
title: '提示',
content: '确定要删除吗?',
cancelText: '取消',
confirmText: '确定',
success: res => {
if (res.confirm) {
this.imgList.splice(i, 1)
}
}
})
}
}
util.js
/**
* 上传文件
* @param string url 请求地址
* @param string src 文件路径
*/
uploadFile: function (url, src) {
uni.showLoading({
title: '请稍候...',
});
return new Promise((resolve, reject) => {
const uploadTask = uni.uploadFile({
url: util.interfaceUrl() + url,
filePath: src,
name: 'file',
header: {
// #ifndef H5
'content-type': 'multipart/form-data',
// #endif
token: util.getToken(),
},
success: function (res) {
uni.hideLoading();
let data = JSON.parse(res.data.replace(/\ufeff/g, '') || '{}');
if (data.code == 0) {
//返回图片地址
resolve(data);
} else {
util.toast(res.msg);
}
},
fail: function (res) {
util.toast('网络不给力,请稍后再试~');
reject(res);
},
});
});
}