uniapp微信小程序需要一个上传图片的组件,不过接口要求将选中的文件转为base64上传,所以对图片上传组件做了二次处理
对组件 uniapp uview upload上传图片后获取图片拼接字符串做了修改调整
需要的功能 uniapp 选择文件并转为base64
需要获取文件后缀名
组件源码
<template>
<u-upload :width='width+"rpx"' :height='height+"rpx"' :fileList="fileList1" @afterRead="afterRead($event)"
@delete="deletePic" name="1" :maxCount="maxCount">
<slot></slot>
</u-upload>
</template>
<script>
import {
UpLoadImg
} from '@/config/api.js'
import configs from '@/config/config.js'
import {
getSuffix
} from '@/utils/util.js'
import {
pathToBase64,
base64ToPath
} from 'image-tools'
export default {
data() {
return {
fileList1: []
}
},
props: {
width: {
type: Number,
default () {
return 200;
}
},
height: {
type: Number,
default () {
return 200;
}
},
maxCount: {
type: Number,
default () {
return 1;
}
},
list: {
type: Array,
default () {
return [];
}
}
},
watch: {
list() {
if (this.list) {
this.fileList1 = []
this.list.forEach((type) => {
var dataurl = {
url: configs.baseUrl + type
}
this.$emit('getdata', type)
this.fileList1.push(dataurl)
});
}
},
},
mounted() {
if (this.list) {
this.fileList1 = []
this.list.forEach((type) => {
var dataurl = {
url: configs.baseUrl + type
}
this.$emit('getdata', type)
this.fileList1.push(dataurl)
});
}
},
methods: {
getlist() {
// this.fileList1()
console.log(this.fileList1)
var list = []
this.fileList1.forEach((type) => {
list.push(type.url)
});
this.$emit('getdata', list)
},
clear() {
this[`fileList${event.name}`] = []
this.getlist()
},
// 删除图片
deletePic(event) {
this[`fileList${event.name}`].splice(event.index, 1)
this.imgList.splice(event.index, 1)
this.getlist()
},
// 新增图片
async afterRead(event) {
// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
let lists = [].concat(event.file)
let fileListLen = this[`fileList${event.name}`].length
lists.map((item) => {
this[`fileList${event.name}`].push({
...item,
status: 'success',
message: '上传中'
})
// this[`fileList${event.name}`].push({
// ...item,
// status: 'uploading',
// message: '上传中'
// })
})
for (let i = 0; i < lists.length; i++) {
const result = await this.uploadFilePromise(lists[i].thumb)
console.log(result)
let item = this[`fileList${event.name}`][fileListLen]
this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
status: 'success',
message: '',
url: result
}))
fileListLen++
}
},
uploadFilePromise(url) {
var that = this;
return new Promise((resolve, reject) => {
if (uni.getStorageSync('token')) {
that.imgToBase64(url).then(base64 => {
// console.log("[转换成base64]", base64)
var base64r = base64.replace('data:image/png;base64,', '')
UpLoadImg({
Suffix: '.' + getSuffix(url),
ImgData: base64r,
}, {
custom: {
auth: true
}
}).then(res => {
if (res.Code == 200) {
resolve(res.Data.FileName)
that.getlist()
}
}).catch(err => {
})
})
}
})
},
imgToBase64(data) {
return new Promise((resolve, reject) => {
pathToBase64(data).then(base64 => {
resolve(base64)
}).catch(error => {
console.error(error)
reject(error)
})
})
},
}
}
</script>
<style>
</style>