封装微信小程序上传图片接口

400 阅读2分钟

小颖公司最近要开发一款小程序,其中有上传图片功能,为了避免后期找不到代码了,小颖写个文章整理下,具体代码如下:

1.封装uni.chooseImage(从本地相册选择图片或使用相机拍照)方法:

小颖用的uniapp所以直接封装的它里面的方法,如果没用的话可以同步至 wx.chooseMedia

	chooseImage(size) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: size, // 默认9
				sizeType: ['original', 'compressed'], //['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
				sourceType: ['album', 'camera'], //['album','camera'], // 可以指定来源是相册还是相机,默认二者都有
				mediaType: ['image'], //['image', 'video'], // 可以指定是图片视频,默认二者都有
				success: function(res) {
					resolve(res)
				},
				fail: function(err) {
					uni.hideLoading();
					reject("选择文件失败", err)
				}
			})
		})
	}

2.封装uni.uploadFile(将本地资源上传到开发者服务器)方法:

小颖用的uniapp所以直接封装的它里面的方法,如果没用的话可以同步至 wx.uploadFile

	uploadFile(file) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				header: {
					'content-type': 'application/json'
				},
				url: 'https://xxx',//上传接口地址
				filePath: file,
				name: 'file',
				success: function(res) {
					var data = res.data;
					resolve(JSON.parse(data))
				},
				fail: function(err) {
					uni.hideLoading();
					reject(err)
				},
			})
		})
	},

3.整合调用的以上方法封装

	// 上传图片 返回一个图片的数组
	async uploadPic(size = 9) {
		let chooseImageResult = await this.chooseImage(size)
		let imgArr = await chooseImageResult.tempFilePaths.map(async (item) => {
			let uploadFileResult = await this.uploadFile(item)
			return uploadFileResult;
		})
		return new Promise((resolve, reject) => {
			Promise.all(imgArr).then((result) => {
				uni.showToast({
					title: '上传成功',
					duration: 3000
				})
				resolve(result)
			}).catch(err => {
				uni.hideLoading();
				reject(err)
			})
		})
	},

4.在 utils 文件下 新建一个 upImages.js 将以上方法整合

export const upLoad = {
	// 上传图片 返回一个图片的数组
	async uploadPic(size = 9) {
		let chooseImageResult = await this.chooseImage(size)
		let imgArr = await chooseImageResult.tempFilePaths.map(async (item) => {
			let uploadFileResult = await this.uploadFile(item)
			return uploadFileResult;
		})
		return new Promise((resolve, reject) => {
			Promise.all(imgArr).then((result) => {
				uni.showToast({
					title: '上传成功',
					duration: 3000
				})
				resolve(result)
			}).catch(err => {
				uni.hideLoading();
				reject(err)
			})
		})
	},
	uploadFile(file) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				header: {
					'content-type': 'application/json'
				},
				url: 'https://xxx',//上传接口地址
				filePath: file,
				name: 'file',
				success: function(res) {
					var data = res.data;
					resolve(JSON.parse(data))
				},
				fail: function(err) {
					uni.hideLoading();
					reject(err)
				},
			})
		})
	},
	chooseImage(size) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: size, // 默认9
				sizeType: ['original', 'compressed'], //['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
				sourceType: ['album', 'camera'], //['album','camera'], // 可以指定来源是相册还是相机,默认二者都有
				mediaType: ['image'], //['image', 'video'], // 可以指定是图片视频,默认二者都有
				success: function(res) {
					resolve(res)
				},
				fail: function(err) {
					uni.hideLoading();
					reject("选择文件失败", err)
				}
			})
		})
	}
}

5.在页面调用

引入:

import { upLoad } from '../../utils/upImages.js';

调用:

		async uploadFileFun(type) {
			let size = 9;
			if (type == 'sf1' || type == 'sf2') {
				size = 1;
			}
			let res = await upLoad.uploadPic(size);
			switch (type) {
				case 'sf1':
					this.imgList.Sfzrxm = res[0].Body.path;
					break;
				case 'sf2':
					this.imgList.Sfzghm = res[0].Body.path;
					break;
				case 'hk':
					this.imgList.Hkb = res.map((item) => item.Body.path);
					break;
				case 'hy':
					this.imgList.Hyzm = res.map((item) => item.Body.path);
					break;
				case 'ls':
					this.imgList.Ls = res.map((item) => item.Body.path);
					break;
				case 'zc':
					this.imgList.Zczm = res.map((item) => item.Body.path);
					break;
				case 'yy':
					this.imgList.Yyzz = res.map((item) => item.Body.path);
					break;
				case 'qt':
					this.imgList.Qt = res.map((item) => item.Body.path);
					break;
			}
			console.log(this.imgList);
		},

6.删除已上传图片:

		deleteImg(type, index) {
			uni.showModal({
				title: '提示',
				content: '确定要删除此照片吗?',
				success: (res) => {
					if (res.confirm) {
						console.log('用户点击确定');
						switch (type) {
							case 'sf1':
								this.imgList.Sfzrxm = '';
								break;
							case 'sf2':
								this.imgList.Sfzghm = '';
								break;
							case 'hk':
								this.imgList.Hkb.splice(index, 1);
								break;
							case 'hy':
								this.imgList.Hyzm.splice(index, 1);
								break;
							case 'ls':
								this.imgList.Ls.splice(index, 1);
								break;
							case 'zc':
								this.imgList.Zczm.splice(index, 1);
								break;
							case 'yy':
								this.imgList.Yyzz.splice(index, 1);
								break;
							case 'qt':
								this.imgList.Qt.splice(index, 1);
								break;
						}
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		}