小程序封装多张图片上传api

export default class Upload{
	constructor(object) {
		this.obj = {
			count:1,
			sizeType:['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
			sourceType:['album','camera'],   // 可以指定来源是相册还是相机,默认二者都有
		}
		if(Object.prototype.toString.call(object) === "[object Object]"){
			Object.assign(this.obj, object);
		}else{
			uni.showToast({
			    title: '参数必须为对象',
			    icon:"icon",
			    duration: 2000
			});
		}
		

		return this;
    }
    // 上传图片 返回一个图片的数组集合
    async uploadPic(){
	    let chooseImageResult = await this.chooseImage()
	    console.log("选择图片",chooseImageResult)

	    let imgArr = await chooseImageResult.tempFilePaths.map(async (item,index) => {
			uni.showLoading({
			    title: `正在上传第${index+1}张`
			});
	    	let uploadFileResult = await this.uploadFile(item)

	    	console.log("上传图片过程",uploadFileResult)
	    	return getApp().globalData.img_prefix + uploadFileResult.data.file.url;
	    })

	    return new Promise((resolve,reject) => {
		    Promise.all(imgArr).then((result)=>{
	  			
	  			uni.hideLoading();
				uni.showToast({
				    title: '上传成功',
				    icon:"none",
				    duration: 2000
				});
				console.log("上传图片结果",result)
				resolve(result)
	       	})
	    }) 
    }
    uploadFile(file){
    	return new Promise((resolve, reject) => {
	        uni.uploadFile({
	          url: 'https://baidu.com/upload/', //此处是你自己上传接口
	          filePath: file,
	          name: 'file',
	          success: function (res) {
	            var data = res.data;
	            resolve(JSON.parse(data))
	            
	          },
	          fail: function (res) {
	            reject("上传失败")
	           
	          },
	          complete: function (res) {
	            uni.hideToast();
	          }
	        })
	    })
    }
    chooseImage(){
    	return new Promise((resolve,reject) => {
    		uni.chooseImage({
			    count: this.obj.count,//1, // 默认9
			    sizeType: this.obj.sizeType,//['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
			    sourceType: this.obj.sourceType,//['album','camera'], // 可以指定来源是相册还是相机,默认二者都有
			    success: function (res) {
			    	// console.log(res)
			    	resolve(res)
			    },
			    fail:function(){
			    	reject("选择文件失败")
			    }
		    })
    	})
    }
}

 

//使用方式
let object = {
    count:1,
    sizeType:['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
    sourceType:['album','camera'],   // 可以指定来源是相册还是相机,默认二者都有
}
let result = await new Upload(object).uploadPic();

  

posted @ 2019-12-27 10:46  剑圣_LLX  阅读(383)  评论(0编辑  收藏  举报