uniapp 使用uview2.0 u-upload组件上传图片文件

uview2.0文档

uni.uploadFile(OBJECT) | uni-app官网

上传图片不能使用uni.request因为data参数不支持fromData数据格式

html 复制代码
<template>
	<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="4" width="180rpx" height="180rpx">
	   <div class="addPic flex justify-center align-center"><u-icon name="plus" :bold="true" color="#172B4D" size="56rpx"></u-icon></div>
	</u-upload>
</template>

<script>
	export default {
		data() {
			return {
				fileList1: [],
			}
		},
		methods:{
			// 删除图片
			deletePic(event) {
				console.log(event);
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			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) {
				console.log("url", url, typeof(url));
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${config.baseUrl}/common/upload/uploadPicFile`, // 仅为示例,非真实的接口地址
						filePath: url,
						name: 'multipartFiles',//这个字段很重要,后端根据这个name获取二进制文件
						formData: {
							type: 11
						},
						success: (res) => {
							console.log("图片接口res", res);
							resolve(res.data.data)
						}
					});
				})
			},
		}

	}
</script>
相关推荐
艾小逗1 小时前
uniapp快速入门教程,内容来源于官方文档,仅仅记录快速入门需要了解到的知识点
小程序·uni-app·app·es6
鸭子嘎鹅子呱15 小时前
uniapp使用高德地图设置marker标记点,后续根据接口数据改变某个marker标记点,动态更新
uni-app·map·高德地图
计算机源码社20 小时前
分享一个基于微信小程序的居家养老服务小程序 养老服务预约安卓app uniapp(源码、调试、LW、开题、PPT)
android·微信小程序·uni-app·毕业设计项目·毕业设计源码·计算机课程设计·计算机毕业设计开题
Angus-zoe1 天前
uniapp+vue+微信小程序实现侧边导航
vue.js·微信小程序·uni-app
Pluto & Ethereal1 天前
uni-app尺寸单位、flex布局于背景图片
uni-app
天空下sky1 天前
uniapp+若依 开发租房小程序源码分享
uni-app
帅过二硕ฅ1 天前
uniapp点击跳转到对应位置
前端·javascript·uni-app
佩淇呢2 天前
uniapp vue3 梯形选项卡组件
前端·vue.js·uni-app
[廾匸]2 天前
uni-app获取设备唯一值、静态IP以及公网IP的方法
uni-app·ip·imei·唯一值
luckycoke2 天前
小程序的右侧抽屉开关动画手写效果
前端·javascript·微信小程序·uni-app