uniapp中的uni-file-picker组件上传多张图片到服务器,可添加,预览,删除图片

前言:在uniapp官方文档中的uni-file-picker组件可实现图片上传功能,官方文档:uniapp官网 中的案例不能完全满足需求,官网中默认的是上传到自带的服务空间

以下是代码:

view代码:
:auto-upload="false"加上这个取消自动上传

<uni-file-picker v-model="filePathsList" :auto-upload="false" file-mediatype="image" mode="grid"
fileMediatype="image"  @select="handleSelect" @delete="handleDelete" />

methods方法

选择图片

async handleSelect(res) {
    
    
	await this.uploadImg(res.tempFilePaths, 1);
},

上传图片

async uploadImg(tempFilePaths, token) {
    
    
	if (!tempFilePaths.length) return;  //如果没有选择图片就退出
	//循环选择图片的张数
	tempFilePaths.map(async () => {
    
    
		const path = tempFilePaths.pop();
		//因为我这个后台给的接口一次只能上传一张图片,所以每循环一次就调用接口上传一次
		const [err, {
    
    data}] = await uni.uploadFile({
    
    
			url: 'https://localhost/file/api/uploadtemp',//后台地址
			filePath: path,
			name: 'file',
			formData: {
    
    
				'user': 'test'
			},
		});
		//因为async返回的是个promise对象,所以要把返回的数据转为对象格式。
		let dataObj = JSON.parse(data)
		//每循环一次就把后台返回的图片地址添加到filePathsList数组
		this.filePathsList.push({
    
    
			url: dataObj.data,
			name: ""
		})
	})
	console.log('filePathsList', this.filePathsList);
	this.uploadImg(tempFilePaths, token);
},

删除图片

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

上传事例:
在这里插入图片描述

参考http://t.csdn.cn/RWQ85这个博主写的,自己修改了一点。

疑问 参考博主的文章中这个代码 this.isGuid 不知道是什么意思,希望有人看到了可以讲解下。

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
}

(自己的笔记)

猜你喜欢

转载自blog.csdn.net/weixin_51014776/article/details/128361316
今日推荐