uni-app 单图上传组件
组件
components/uploadImg.vue
<template>
<view class="container">
<image v-if="UploadUrl" @click="uploadImg()" :style="{'width': size[0] + 'rpx', height: size[1] + 'rpx' }"
:src="UploadUrl" />
<image v-else @click="uploadImg" :style="{'width': size[0] + 'rpx', height: size[1] + 'rpx' }"
:src="defaultImg" />
<image v-if="UploadUrl"
:style="{width: '34rpx', height: '34rpx', position: 'absolute' , top: '0', left: size[0] + 'rpx' }"
src="../static/close.png" @click="deleteImg()" />
</view>
</template>
<script>
import defaultImg from '../static/plus.png'
export default {
name: 'uploadImg',
props: {
size: {
type: Array,
default: () => [200, 200]
},
defaultImg: {
type: String,
default: defaultImg
}
},
data() {
return {
UploadUrl: ''
}
},
methods: {
uploadImg() {
var that = this;
uni.chooseImage({
count: 1, // 选择数量限制
sizeType: ['original', 'compressed'], // 原图、压缩图
sourceType: ['album', 'camera'], // 相册、拍照选择
success: async (res) => {
const tempFilePaths = res.tempFiles[0].path;
// 图片上传
uni.showLoading({
title: '图片上传中...'
});
const uploadTask = uni.uploadFile({
url: that.$host +'api/common/upload', // post请求地址
filePath: tempFilePaths,
name: 'file', // 待确认
header: {
'Content-Type': 'multipart/form-data',
'token': uni.getStorageSync('token')
},
success: function(res) {
const Upres = JSON.parse(res.data)
if (Upres.code == 0) {
uni.showModal({
title: '上传失败',
content: Upres.msg,
})
} else {
that.UploadUrl = Upres.data.fullurl;
setTimeout(() => {
that.$emit('upload', {
url: Upres.data.url
})
}, 200)
}
},
fail: function(failed) {
console.log('Error:', failed.data);
},
complete: () => {
uni.hideLoading();
}
});
}
})
},
//删除图片
deleteImg() {
var that = this;
uni.showModal({
title: '提示',
content: '确定要删除这张图片吗',
success: (res) => {
if (res.confirm) {
that.UploadUrl = '';
setTimeout(() => {
that.$emit('upload', {
url: ''
})
}, 200)
} else if (res.cancel) {
}
}
})
},
},
}
</script>
<style>
.container {
position: relative;
}
</style>
使用
<template>
<view class="container">
<view class="new-list-item">
<view class="title">
略缩图:
</view>
<view class="list-item-image">
<uploadImg :size="[150, 150]" @upload="upload"></uploadImg>
</view>
</view>
</view>
</template>
<script>
import uploadImg from '@/components/uploadImg.vue'
export default {
components: {
uploadImg,
},
data() {
return {
form: {
litpic: '',
}
}
},
methods: {
//获取子组件的图片url
upload(e) {
// console.log('e ==>',e);
this.form.litpic = e.url;
},
}
}
</script>
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析