uniapp 上传文件 封装方法

封装: 

import {baseURL} from './request.js'
import {toast,toa} from './toast.js'
export const uploadFile = (tempFilePaths,data)=>{
	return new Promise((resolve, reject) => {
	toa.loading('上传中..')
	 uni.uploadFile({
			url: baseURL + '/common/upload', //仅为示例,非真实的接口地址
			filePath: tempFilePaths,
			name: 'file',
			formData: {...data,token:uni.getStorageSync('token') || ''},
			success: (res) => {
				toa.hideLoading()
				console.log(res);
				if(res.statusCode==200){
					resolve(JSON.parse(res.data).data)
				}
			},
			fail:(err)=>{
				toa.hideLoading()
				toast(JSON.parse(err.data).msg)
				console.log(err,'上传报错');
				// return 
				reject(err)
			}
		})
	})
}

baseUrl: 基地址 

toast toa 是单独封装的提示  

调用upload方法时可以传入两个参数 第一个是图片路径 第二个是formdata的 其他参数

 使用:

upLoadImg() {
				uni.chooseImage({
					count: 9 - that.imgList.length, //默认9
					sizeType: ['original'], //可以指定是原图还是压缩图,默认二者都有 , 'original','compressed'
					sourceType: ['album'], //从相册选择
					success: async function(res) {
						console.log(JSON.stringify(res.tempFilePaths));
						const tempFilePaths = res.tempFilePaths;
						for (let i = 0; i < tempFilePaths.length; i++) {
							const result = await uploadFile(tempFilePaths[i])
							that.imgList.push(result)
						}
					}
				});
			},

注意 async await的位置哈 否则会拿不到数据

你可能感兴趣的:(小程序复用,vue,vue.js,javascript,前端)