uniapp封装promise图片上传方法(ts版,js的话把参数类型去掉就行)
第一步:新建文件夹services
第二步:新建文件request.ts
//服务器接口地址 const baseURL:string='http://xxxxxx' //本地调试接口地址 // const baseURL:string='http://xxxxxx' // 封装公共上传图片 function upload(num:number,imglength:number,type?:string | undefined ) { //num表示限制图片上传数量 imglength表示已经上传图片的数量 let uploads :any[] = []; return new Promise(function(presolve, preject){ let sourceType:string[]; if(type==undefined){ sourceType = ['album','camera'] }else if(type=='album'){ sourceType = ['album'] }else if(type=='camera'){ sourceType = ['camera'] } uni.chooseImage({ count: num-imglength, sizeType: ['compressed'], sourceType: sourceType, success(res: any) { uni.showLoading({ title: '上传中...', mask: true, }) for (var i = 0; i < res.tempFilePaths.length; i++) { // console.log(res.tempFilePaths[i]) uploads[i] = new Promise(function(resolve, reject){ uni.uploadFile({ url: baseURL +'/customer/upload_file', filePath: res.tempFilePaths[i], name: 'file', header: { 'content-type': 'application/json', "X-Auth-Token": uni.getStorageSync('token') }, success(res: any) { uni.hideLoading() resolve(JSON.parse(res.data).payload); }, fail(err: any) { uni.showToast({ title:err }) console.log(err); } }) }) } Promise.all(uploads).then(res=>{ //图片上传完成 presolve(res) wx.hideLoading() }).catch(err=>{ preject(err) wx.hideLoading() wx.showToast({ title:'上传失败请重试', icon:'none' }) }) } }) }) } export {upload,baseURL}
需要的文件.vue引入需要的接口
<script lang="ts">
import { upload} from '../../../services/request';
export default Vue.extend({
data() {
return {
img:[]
}
},
methods: {
async uploadImg() {
const imgFile: any = await upload(9,this.img.length)
this.img = this.img.concat(imgFile)
},
},
});
</script>
再忙也别忘记学习