uniapp APP 上传文件

javascript 复制代码
/**
	 * 上传文件
	 */
	uploadPhoneFile:function(callback,params = {}) {
		let fileType = ['.pdf','.doc','.xlsx','.docx','.xls']
		// #ifdef APP-PLUS
			plus.io.chooseFile({
				title: '选择文件',  
				filetypes: ['doc', 'docx'], // 允许的文件类型  
				multiple: false, // 是否允许多选  
			},(e)=>{
				const tempFilePaths = e.files
				//第二步:把选择的文件上传到服务器
				Promise.all(tempFilePaths.map((tempFile) => {
					return new Promise((resolve,reject) => {
						uni.uploadFile({
							url: process.uniEnv.baseUrl + '/file/attch/upload',
							filePath: tempFile,
							name: 'file',
							header: {
								Authorization: 'Bearer ' + utils.CacheStorage("access_token"),//  uni.getStorageSync('access_token'),
								terminal:'app'
							},
							success: (uploadFileRes) => {
								// console.log('asdaggg',JSON.parse(uploadFileRes.data));
								let { code,data,msg } = JSON.parse(uploadFileRes.data)
								if(code === 200) {
									resolve(data)
								} else {
									uni.showToast({
										title: msg,
										icon: 'none'
									})
									reject('上传失败')
								}
							},
							fail: (error) => {
								reject(error)
							}
						});
					})
				})).then(images => {
					// console.log('上传成功>>>>>>',images)
					callback(images)
				})
			});
		// #endif
		
		// #ifndef APP-PLUS
		uni.chooseFile({
			//第一步:选择文件
			count: 1, //默认100
			extension: fileType,
			success: function (res) {
				const tempFilePaths = res.tempFilePaths;//若果只选择一个文件,这个文件就是数组的第一个元素
				//第二步:把选择的文件上传到服务器
				Promise.all(res.tempFilePaths.map((tempFile) => {
					return new Promise((resolve,reject) => {
						uni.uploadFile({
							url: '/dev-api/file/attch/upload',
							filePath: tempFile,
							name: 'file',
							header: {
								Authorization: 'Bearer ' + utils.CacheStorage("access_token"),//  uni.getStorageSync('access_token'),
								terminal:'app'
							},
							success: (uploadFileRes) => {
								console.log('asdaggg',JSON.parse(uploadFileRes.data));
								let { code,data,msg } = JSON.parse(uploadFileRes.data)
								if(code === 200) {
									resolve(data)
								} else {
									uni.showToast({
										title: msg,
										icon: 'none'
									})
									reject('上传失败')
								}
							},
							fail: (error) => {
								reject(error)
							}
						});
					})
				})).then(images => {
					console.log('asdjgllgl;s',images)
					callback(images)
				})
			}
		})
		// #endif
	}

写法很粗糙,只自己用作记录,可以再优化与扩展。

相关推荐
GISer_Jing1 小时前
AI营销增长:4大核心能力+前端落地指南
前端·javascript·人工智能
明远湖之鱼1 小时前
一种基于 Service Worker 的渐进式渲染方案的基本原理
前端
前端小端长2 小时前
Vue 中 keep-alive 组件的原理与实践详解
前端·vue.js·spring
FeelTouch Labs2 小时前
Nginx核心架构设计
运维·前端·nginx
雪球工程师团队3 小时前
别再“苦力”写后台,Spec Coding “跑” 起来
前端·ai编程
m0_471199633 小时前
【场景】前端怎么解决离线收银、数据同步异常等场景问题
前端·javascript
Curvatureflight3 小时前
前端性能优化实战:从3秒到300ms的加载速度提升
前端·人工智能·性能优化
用户99045017780093 小时前
ruoyi集成dmn规则引擎
前端
袋鱼不重3 小时前
AI入门知识点:什么是 AIGC、多模态、RAG、Function Call、Agent、MCP?
前端·aigc·ai编程