本来是使用uview就是这样的
<template>
<u-upload
:fileList="fileList1"
@afterRead="afterRead"
@delete="deletePic"
name="1"
multiple
:maxCount="9"
></u-upload>
</template>
<script>
export default {
data() {
return {
fileList1: [],
}
},
methods:{
// 删除图片
deletePic(event) {
this[`fileList${event.name}`].splice(event.index, 1)
},
// 新增图片
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
})
})
for (let i = 0; i < lists.length; i++) {
const result = await uploadFilePromise(lists[i].url)
let item = this[`fileList${event.name}`][fileListLen]
this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
status: 'success',
message: '',
url: JSON.parse(result).data
}))
fileListLen++
}
uploadFilePromise(url) {
return new Promise((resolve, reject) => {
let a = uni.uploadFile({
url: 'https://test.pc.yscwr.com/api/image/upload', // 测试地址
filePath: url,
name: 'file',
success: (res) => {
// setTimeout(() => {
resolve(res.data)
// }, 1000)
}
});
})
};
},
}
}
</script>
注:
this[`fileList${event.name}`] 其实就是 this.fileList1
这样写的话 这个参数就是动态的,比如一个文件中有多个上传图片功能,你可以写多个html,但只需要写一个js
新建一个文件image.js 进行封装
//直接导出这个方法
export function uploadImg(event,fileList) {
return new Promise((resolve,reject)=>{
// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
let lists = [].concat(event.file)
let fileListLen = fileList.length
lists.map((item) => {
fileList.push({
...item
})
})
// 这块把uview的改了一下 不用单独封装上传功能
for (let i = 0; i < lists.length; i++) {
uni.uploadFile({
url: '192.111.111.111', // 测试地址
filePath: lists[i].url, // 文件路径
name: 'file',
success: (res) => {
let resolveData = {
data: res.data,
fileListLen: fileListLen
}
// 成功之后返回resolveData
resolve(resolveData);
fileListLen++
}
});
}
})
}
使用
<template>
<u-upload
:fileList="fileList"
@afterRead="afterRead"
@delete="deletePic"
name="1"
multiple
:maxCount="9"
></u-upload>
</template>
<script>
// 导入这个方法
import {uploadImg} from '../../utils/image.js'
export default {
data() {
return {
fileList: [],
}
},
methods:{
// 删除图片
deletePic(event) {
this.fileList.splice(event.index, 1)
},
async afterRead(event){
//使用这个封装
const result = await uploadImg(event,this.fileList)
let item = this.fileList[result.fileListLen]
this.fileList.splice(result.fileListLen, 1, Object.assign(item, {
status: 'success',
message: '成功',
url: JSON.parse(result.data).data
}))
}
}
}
</script>