文章目录
- html代码
- 功能实现
- css样式代码
html代码
<uni-file-picker@select="onFileSelected"@cancel="onFilePickerCancel"limit="1"class="weightPage-upload-but"file-mediatype="image"></uni-file-picker><imageclass="weightPage-item-upload-img"v-if="weightData.img_url":src="weightData.img_url"mode=""></image><imageclass="weightPage-item-upload-img"v-elsesrc="@/static/checkDetails/upload.png"mode=""></image>
用image覆盖,就能实现完全自定义上传样式的功能(也能用其他的覆盖)
上传前:
上传后:
功能实现
data() {return {weightData: {img_url: "",},};},methods: {onFileSelected(e) {// 获取选中的文件路径const filePath = e.tempFiles[0].url;console.log(filePath);// 调用上传图片的方法this.uploadImage(filePath);},async uploadImage(filePath) {try {let formData = new FormData();formData.append("file", {url: filePath,name: "image.jpg",type: "image/jpeg",});// 转换为普通 Objectconst formDataObj = {};for (let [key, value] of formData.entries()) {formDataObj[key] = value;}/*#ifdef MP-WEIXIN*/// 从微信小程序的本地缓存中取出 tokenlet wxToken = wx.getStorageSync("token");let wxbaseURL = wx.getStorageSync("baseURL");// 检查是否成功获取到值if (wxToken) {uni.uploadFile({url: `${wxbaseURL}...`, //需要传图片的后台接口filePath: filePath, // 上传图片 通过uni-app的uni-file-picker组件 函数返回name: "image", //文件名字header: {Authorization: "Bearer " + wxToken,},formData: formDataObj,success: (res) => {const { data } = JSON.parse(res.data);console.log(data);this.weightData.img_url = data.url;uni.showToast({title: "图片上传成功",icon: "success",duration: 2000, // 提示持续时间,单位为毫秒});},fail: (e) => {console.log(e);},});}/*#endif*//*#ifdef H5*/let Token = localStorage.getItem("token");let baseURL = localStorage.getItem("baseURL");// 检查是否成功获取到值if (Token) {uni.uploadFile({url: `${baseURL}...`, //需要传图片的后台接口filePath: filePath, // 上传图片 通过uni-app的uni-file-picker组件 函数返回name: "image", //文件名字header: {Authorization: "Bearer " + Token,},formData: formDataObj,success: (res) => {console.log(JSON.parse(res.data));const { data } = JSON.parse(res.data);console.log(data);this.weightData.img_url = data.url;uni.showToast({title: "图片上传成功",icon: "success",duration: 2000, // 提示持续时间,单位为毫秒});},fail: (e) => {console.log(e);},});}/*#endif*/// 可以添加上传进度监听等额外逻辑} catch (error) {console.error("上传图片时发生错误", error);}},onFilePickerCancel() {console.log("取消选择");// 可以在这里处理取消选择的逻辑},},
css样式代码
隐藏样式的重点是 opacity: 0;
.weightPage-upload-but {position: absolute;width: 279px;height: 100px;z-index: 1;left: 0px;opacity: 0;padding: 10px;}.weightPage-item-upload-img {width: 80px;height: 78px;border-radius: 10px;}.weightPage-item-upload-text {font-size: 12px;font-weight: 500;line-height: 19px;color: rgba(153, 153, 153, 1);flex: 1;padding: 10px;}
您好,我是肥晨。
欢迎关注我获取前端学习资源,日常分享技术变革,生存法则;行业内幕,洞察先机。