项目实现页面大致逻辑如下,完整页面实现逻辑可移步《Uni-app 实现图片上传、删除、预览、压缩》下载。
视图渲染
<template>
<view class="center">
<!-- 上传图片 -->
<view class="uploadClass">
<view class="imgClass" v-for="(item, i) in imgList" :key='i' @click="viewImage(i, imgList)">
<image style="width: 100%;height: 100%;" :src="item"></image>
<view @click.stop="delImg(i, imgList, imgsID)" style="display: inline;">
<uni-icons type="closeempty" class="closeClass" size="20"></uni-icons>
</view>
</view>
<view v-show='curTotal < 3' class="cameraClass" @tap="upload">
<image style="width: 48rpx; height: 38rpx;" src="@/static/appCenter/zhaoxiangji@2x.png"></image>
</view>
<!-- 图片数量提示 -->
<view class="totalClass">{{curTotal}}/3</view>
</view>
</template>
JS逻辑层-图片上传
// 图片选择上传
upload() {
var _self = this;
// 图片选择,只支持一次选择一张图片
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], //从相册、相机选择
success: function (res) {
console.log('res:', res)
_self.curTotal++;
_self.imgList.push(res.tempFilePaths[0]);
const tempFilePaths = res.tempFilePaths[0];
// 图片上传
const uploadTask = uni.uploadFile({
url : 'http://22.189.25.91:9988/admin/sys-file/upload', // post请求地址
filePath: tempFilePaths,
name: 'file', // 待确认
header: {
'Content-Type': 'multipart/form-data',
'Authorization': getApp().globalData.token || 'Basic YXBwOmFwcA=='
},
success: function (uploadFileRes) {
console.log('Success:', uploadFileRes);
_self.imgsID.push(JSON.parse(uploadFileRes.data).data.fileId);
console.log('\_self.imgsID:', _self.imgsID)
},
fail: function (uploadFileFail) {
console.log('Error:', uploadFileFail.data);
},
complete: ()=> {
console.log('Complete:');
}
});
},
error : function(e){
console.log(e);
}
});
}
JS逻辑层-图片预览
/\*\*
\* 图片预览
\* @param {Object} i 选择的图片索引
\* @param {Object} imgList 自行封装的图片数组
\*/
viewImage(i, imgList) {
let imgurl = []
imgList.forEach(item => imgurl.push(item))
uni.previewImage({
urls: imgurl,
current: imgList[i]
});
}
JS逻辑层-图片删除
/\*\* 图片删除
\* @param {Object} i 删除图片的索引
\* @param {Object} imgList 自行封装的图片数组
\*/
delImg(i, imgList, imgsID) {
uni.showModal({
title: '提示',
content: '确定要删除照片吗?',
cancelText: '取消',
confirmText: '确定',
success: res => {
if(res.confirm) {
imgList.splice(i, 1);
imgsID.splice(i, 1);
this.curTotal--;
}
}
})
}
}
JS逻辑层-图片压缩
// src: 压缩转换原始图片的路径
// \_this: 当前的this,如果不想传递this可将该函数改为箭头函数
// callback: 回调函数,详情chooseImage方法
function compressImage(src, \_this, callback) {
var dstname = "\_doc/IMG-" + (new Date()).valueOf() + ".jpg"; //设置压缩后图片的路径
var width, height, quality;
width = "80%";
height = "80%";
quality = 80;
// 具体情况可查看HTML5+文档 ===> http://www.html5plus.org/doc/zh\_cn/zip.html#plus.zip.compressImage
plus.zip.compressImage({
src: src,
dst: dstname,
overwrite: true,
quality: quality,
width: width,
height: height
},
function(event) {
callback(event.target, dstname, _this);
},
function(error) {
return src;
});
}
注意⚠️:在图片上传之前进行图片压缩,由于图片压缩时间过长,应采用
await
上传图片之前先压缩,否则上传会比压缩先执行。
应用实现效果如下: