当前位置:   article > 正文

uniapp中的uni-file-picker组件上传多张图片到服务器,可添加,预览,删除图片_uni-file-picker详细使用教学

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" />
  • 1
  • 2

methods方法

选择图片

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

上传图片

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);
},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

删除图片

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

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

参考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
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

(自己的笔记)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/183473
推荐阅读
相关标签
  

闽ICP备14008679号