1.新建一个以hello uniapp为模板的项目
2.进入feedback页面
<view class="feedback-body feedback-uploader">
<view class="uni-uploader">
<view class="uni-uploader-head">
<view class="uni-uploader-title">点击预览图片</view>
<!-- 展示已选中图片数量 -->
<view class="uni-uploader-info">{{imageList.length}}/8</view>
</view>
<view class="uni-uploader-body">
<view class="uni-uploader__files">
<!-- 遍历存放图片的数组 -->
<block v-for="(image,index) in imageList" :key="index">
<view class="uni-uploader__file" style="position: relative;">
<!-- 将数组中的图片url赋值给src属性,并提供点击预览的方法 -->
<image class="uni-uploader__img" :src="image" @tap="previewImage(index)"></image>
<!-- 点击 x 的时候删除图片 -->
<view class="close-view" @click="close(index)">x</view>
</view>
</block>
<!-- 图片已选中八张时,关闭按钮 -->
<view class="uni-uploader__input-box" v-show="imageList.length < 8">
<view class="uni-uploader__input" @tap="chooseImg"></view>
</view>
</view>
</view>
</view>
</view>
3.选择图片
chooseImg() {
var _this = this;
//选择图片
uni.chooseImage({
sourceType: ["camera", "album"],//拍摄照片或者相册中选取
sizeType: "compressed",//照片类型(这里选择进行压缩)
count: 8 - this.imageList.length,//可以选中的最大数量为8张
success: (res) => {
this.imageList = this.imageList.concat(res.tempFilePaths);//将临时图片路径存入图片数组中
res.tempFilePaths.forEach(items=>{
uni.showLoading({
title: '正在上传中...'
});
<!--上传图片-->
uni.uploadFile({
url: _this.serverUrl + '/system/file/uploadSingle.json',//图片上传接口
filePath: items,
fileType: 'image',
name: 'file',
header: {
'Authorization': 'Bearer ' + this.getGlobalToken(),
'Content-Type': 'multipart/form-data'
},
success: (res) => {
uni.hideLoading();
var data = JSON.parse(res.data);
uni.showToast({
title: data.message
});
if (data.code == 0) {
var newFile=data.data;
//照片数组
this.newFiles.push(newFile)
}
},
fail: (err) => {
uni.hideLoading();
console.error(err);
uni.showToast({
title: '上传失败'
});
}
});
})
}
})
},
4.上传成功后,会将照片构造为自己定义的照片对象,存入照片数组中,如下图
页面效果:点击x删除图片
5.点击完成按钮后,图片数组中的图片对象,会随着接口上传至后台,这一步之后,前端页面已完成
//照片
addParam['newFiles'] = this.newFiles;
uni.request({
url: _this.serverUrl + '/shizheng/municipalApprovalProjectSiteInvestigationService/add.json',
data: JSON.stringify(_this.getSignData(addParam)),
method:'POST',
header: {
'Authorization': 'Bearer ' + _this.getGlobalToken(),
'Content-Type': 'application/json;charset=UTF-8'
},
timeout: 10 * 60 * 1000,
success: res => {
uni.hideLoading();
console.log(res);
if (res.data.code == 0) {
uni.$emit('add',{msg:'页面更新'});
setTimeout(function() {
uni.navigateBack({
delta: 1
});
}, 500);
}
},
fail: e => {
uni.hideLoading();
console.error(e);
uni.showToast({
title: e.data.message || '请求出错'
});
}
});