赞
踩
<uni-file-picker @select="onFileSelected" @cancel="onFilePickerCancel" limit="1" class="weightPage-upload-but" file-mediatype="image" ></uni-file-picker> <image class="weightPage-item-upload-img" v-if="weightData.img_url" :src="weightData.img_url" mode="" > </image> <image class="weightPage-item-upload-img" v-else src="@/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", }); // 转换为普通 Object const formDataObj = {}; for (let [key, value] of formData.entries()) { formDataObj[key] = value; } /*#ifdef MP-WEIXIN*/ // 从微信小程序的本地缓存中取出 token let 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("取消选择"); // 可以在这里处理取消选择的逻辑 }, },
隐藏样式的重点是 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; }
您好,我是肥晨。
欢迎关注我获取前端学习资源,日常分享技术变革,生存法则;行业内幕,洞察先机。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。