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>
相关推荐
十五春会9 小时前
【uniapp】App平台展示pdf文件
pdf·uni-app
请叫我欧皇i10 小时前
保姆级教程vscode创建uniapp vue3+ts+pinia项目并实现自动导入、打包功能
ide·vscode·uni-app
海鸥两三10 小时前
Uni-App(Vue3 + TypeScript)项目结构详解 ------ 以 Lighting-UniApp 为例,提供源代码
vue.js·typescript·uni-app·1024程序员节
知识分享小能手10 小时前
uni-app 入门学习教程,从入门到精通,uni-app 企业项目实战:鲁嗑瓜子项目开发知识点(9)
前端·javascript·学习·微信小程序·小程序·uni-app·vue
知识分享小能手10 小时前
uni-app 入门学习教程,从入门到精通,uni-app中uCharts组件学习((8)
vue.js·学习·ui·微信小程序·小程序·uni-app·echarts
社会底层无业大学生13 小时前
uniapp微信小程序简单表格展示
微信小程序·小程序·uni-app·vue·1024程序员节
2501_9159184116 小时前
iOS 26 查看电池容量与健康状态 多工具组合的工程实践
android·ios·小程序·https·uni-app·iphone·webview
2501_9159090618 小时前
iOS 架构设计全解析 从MVC到MVVM与使用 开心上架 跨平台发布 免Mac
android·ios·小程序·https·uni-app·iphone·webview
2501_916008891 天前
Web 前端开发常用工具推荐与团队实践分享
android·前端·ios·小程序·uni-app·iphone·webview
2501_915921431 天前
“HTTPS 个人化”实战,个人站点与设备调试的部署、验证与抓包排查方法
网络协议·http·ios·小程序·https·uni-app·iphone