提前申明,该组件上传服务器为公司内部的服务器,使用时将接口替换为你自己公司的接口就好,或者使用腾讯云也可以 ,$rbj.upload 这是我用的接口函数,你可以自行使用axios
1、uploadImgComponent组件
<template>
<view class="container">
<image v-if="afterUploadUrl" @click="uploadImg()" :style="{'width': size[0] + 'rpx', height: size[1] + 'rpx' }" :src="afterUploadUrl" />
<image v-else @click="uploadImg" :style="{'width': size[0] + 'rpx', height: size[1] + 'rpx' }" :src="defaultImg" />
</view>
</template>
<script>
import defaultImg from '../../../static/uploadImg/upload.png'
export default {
name: 'uploadImgComponent',
props: {
size: {
type: Array,
default: () => [200, 200]
},
defaultImg: {
type: String,
default: defaultImg
}
},
data() {
return {
afterUploadUrl: ''
}
},
methods: {
uploadImg() {
uni.chooseImage({
count: 1, //默认1
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: async (res) => {
// this.$rbj.upload 这是我用的接口函数,你可以自行使用axios
const uploadResult = await this.$rbj.upload("uploadFile", res.tempFiles[0].path, null, "file", true)
const { data: { url } } = JSON.parse(uploadResult.data)
this.afterUploadUrl = `${this.$rbj.$reqAddress}/file/statics${url}`
this.$emit('upload', this.afterUploadUrl)
}
})
},
},
}
</script>
2、组件内使用
// 注册
import uploadImgComponent from './components/uploadImgComponent.vue'
components: { uploadImgComponent }
// html中
<uploadImgComponent :size="[150, 150]" @upload="res => item.resultPhoto = res"></uploadImgComponent>