小程序图片上传

孤街浪徒 提交于 2020-01-31 06:47:03

最近用小程序做上传,发现只能单图上传,刚开始很是头疼,由于图片和内容提交是分开的两个不同的接口,图片不是必填项,刚开始很是头疼,请教了一下别人,emmmmm,解决了(uni-app)

主要用到的是es6中的promise,一种异步的执行,Promise 对象是由关键字 new 及其构造函数来创建的。
有兴趣的同学可以直接去阮一峰大佬的网站学习:es6学习网站

直接上代码:

在这之前要先选择图片,直接用uni.chooseImage这个api就行,
在成功的回调里面循环选择的图片数组
success: (res) => {
res.tempFilePaths.forEach((item,index) => {
this.photoArr = res.tempFiles
var photoPath = this.photoArr
this.imgArr = res.tempFilePaths
})
}

1、首先是图片上传的代码,我把他封装成了一个方法,最后直接调用就可以了
upImg(imgSrc){//上傳圖片方法封裝
console.log(imgSrc)
return new Promise((resolve,reject) => {
uni.uploadFile({
url:this.serverUrl + ‘image’,
filePath:imgSrc,
name:‘file’,
success:(res) => {
this.upImgArr.push(res.data);
resolve()
},
fail:(res) => {
uni.showToast({
icon:‘none’,
title:‘上傳失敗’
})
reject()
}
})
})
},

2、然后是内容的提交
submit(){//提交方法封裝
let imgSrc = ‘’
this.upImgArr.forEach((img, index) => {
index == this.upImgArr.length - 1
? imgSrc = imgSrc + img
: imgSrc = imgSrc + img + ‘,’
})
console.log(imgSrc)
uni.request({
url:this.serverUrl + ‘user/feedback’,
method:‘GET’,
data:{
openid:this.openId,
content:this.feedBackContent,
mobile:this.phone,
file:imgSrc
},
success: (res) => {
if(res.data.code == 200){
uni.showToast({
icon:‘success’,
title:‘提交成功’
})
setTimeout(() => {
uni.navigateTo({
url:"…/mine/mine"
})
})
console.log(this.upImgArr);
}
}
})
},

3、最后在点击提交的时候
submitFeedBack(){
if(this.feedBackContent == ‘’){
uni.showToast({
icon:‘none’,
title:‘您還沒有填寫需要反饋的內容’
})
return false
} else {
if(!(/^1[3456789]\d{9}$/.test(this.phone))){
uni.showToast({
icon:‘none’,
title:‘請輸入正確的手機號’
})
} else {
let promise = []
this.imgArr.forEach((item) => {
promise.push(this.upImg(item))
})
console.log(this.upImgArr);
Promise.all(promise).then(() => {
this.submit()
})
}
}
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!