前言:在uniapp官方文档中的uni-file-picker组件可实现图片上传功能,官方文档:uni-app官网 中的案例不能完全满足需求,在接口上传失败的时候,需要页面不回显失败的图片,仅回显显示上传成功的图片,因为多图异步上传顺序的问题,可能会导致同时操作list,以至于删除图片出错。所以我才用多图同步顺序上传来规避这个问题。

以下是代码:

view代码:

<uni-file-picker :value="filePathsList" :auto-upload="false" file-mediatype="image" mode="grid"
			file-extname="png,jpg" :limit="4" @select="handleSelect" @delete="handleDelete" @success="success" />

上传时的select代码:

async handleSelect(res) { // 上传图片
    await this.uploadImg(res.tempFilePaths,1);
},

uploadImg实现

async uploadImg(tempFilePaths, token) {
    console.log(token)
    if (!tempFilePaths.length) return;
    const path = tempFilePaths.pop();
    this.filePathsList.push({url:path,name:""})
    const [err, {data}] = await uni.uploadFile({
        url: 'https://localhost/file/api/uploadtemp',
        filePath: path,
        name: 'file',
        header: {
            Authorization: token,
            "Content-Type": "multipart/form-data",
        }
    });
    console.log("err", err)
    console.log("data", data)
    if (!this.isGuid(data)) {
        // upload fail
        this.filePathsList.pop()
        uni.showToast({
            title: "上传失败",
            icon: "none"
        })
    }else{
        // upload success
        this.filePathsList[this.filePathsList.length - 1].name = data
    }
    this.uploadImg(tempFilePaths,token);
},

删除代码:

handleDelete(err) { // 删除图片
    const num = this.filePathsList.findIndex(v => v.url === err.tempFilePath);
    this.filePathsList.splice(num, 1);
},

上传事例:

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐