// 新增图片 async afterRead(event) { // 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式 let lists = [].concat(event.file) let fileListLen = this[`fileList${event.name}`].length lists.map((item) => { this[`fileList${event.name}`].push({ ...item, status: 'uploading', message: '上传中' }) }) for (let i = 0; i < lists.length; i++) { const result = await this.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: result })) fileListLen++ } }, uploadFilePromise(url) { return new Promise((resolve, reject) => { let a = uni.uploadFile({ url: 'http://192.168.2.21:7001/upload', // 仅为示例,非真实的接口地址 filePath: url, name: 'file', formData: { user: 'test' }, success: (res) => { setTimeout(() => { resolve(res.data.data) }, 1000) } }); }) }
时间: 2024-03-17 18:39:37 浏览: 98
这段代码实现了在 uniapp 中新增图片上传,其中包括以下步骤:
1. 在模板中通过 `uni-upload` 组件实现文件上传:
```
<template>
<div>
<div>
<div>单个文件上传</div>
<uni-upload :name="'1'" :file-list="fileList1" :max-count="1" :show-file-list="true" :preview-image="true" @after-read="afterRead"></uni-upload>
</div>
<div>
<div>多个文件上传</div>
<uni-upload :name="'2'" :file-list="fileList2" :max-count="3" :show-file-list="true" :preview-image="true" @after-read="afterRead"></uni-upload>
</div>
</div>
</template>
```
2. 在 `afterRead` 方法中实现文件上传:
```
async afterRead(event) {
let lists = [].concat(event.file)
let fileListLen = this[`fileList${event.name}`].length
lists.map((item) => {
this[`fileList${event.name}`].push({
...item,
status: 'uploading',
message: '上传中'
})
})
for (let i = 0; i < lists.length; i++) {
const result = await this.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: result
}))
fileListLen++
}
}
```
3. 在 `uploadFilePromise` 方法中使用 Promise 实现文件上传:
```
uploadFilePromise(url) {
return new Promise((resolve, reject) => {
let a = uni.uploadFile({
url: 'http://192.168.2.21:7001/upload', // 仅为示例,非真实的接口地址
filePath: url,
name: 'file',
formData: {
user: 'test'
},
success: (res) => {
setTimeout(() => {
resolve(res.data.data)
}, 1000)
}
});
})
}
```
这样就可以在 uniapp 中实现图片上传了。需要注意的是,此处的代码中使用了 `async/await` 和 Promise,需要在项目中启用 async/await 语法和 Promise 支持。
阅读全文