微信小程序官方文档上传图片贼简单
wx.chooseImage({
success (res) {
const tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
name: 'file',
formData: {
'user': 'test'
},
success (res){
const data = res.data
//do something
}
})
}
})
但其实官方案列只能上传一张图片
要想像微信那样实现发九宫格朋友圈的功能,官网案例是远远不够的。
想要同时上传用户的内容及图片,需要做的操作就不止这一点点啦
首先,我把wx.uploadFile封装了一下下,
function Upload (url ,file ,data, cb ){
var promise = new Promise(function(resolve,rehect){
for(var i =0;i<file.length;i++){ //遍历图片
wx.uploadFile({
method: 'POST',
url: config.HTTP_BASE_URL + url,
filePath: file[i],
name: "file",
formData: data,
success: (res) => {
if (typeof (res.data) == "string") {
typeof cb == "function" && cb(JSON.parse(res.data), "");
} else {
typeof cb == "function" && cb(res.data, "");
}
},
fail: (err) => {
typeof cb == "function" && cb(null, err.errMsg);
},
});
}
})
return promise;
};
然后
data: {
images: [],
coverstatus:false,
clock:false,
coversrc: "/images/clockSuccess.png",
covertitle: "恭喜您打卡成功!",
stage: 2,
height: 20,
focus: true,
contents:0,
userInput:""
},
bindWordLimit: function (e) {
var self = this;
self.setData({
contents: e.detail.value
});
},
orderMeeting: function () {
var self = this;
var content = self.data.contents;
var file= self.data.images;
var length = file.length;
console.log("上传",file)
var requestData = {}
common.checkLogin(function (access_token) {
// wx.showLoading() //显示loding提示框
requestData["sessionKey"] = access_token
var data = {
content: content,
file: file,
sessionKey: requestData.sessionKey
}
httpHelper.httpUpload('/moments/clock',file, data, (res) =>{
// wx.hideLoading() //隐藏loding提示框
console.log("返回值",res)
if (res.data.statusCode === 1000){
}else{
console.log("错误")
}
}, access_token)
})
},
onLoad(options) {
$init(this)
},
delImg(e) {
const idx = e.target.dataset.idx;
this.data.images.splice(idx, 1)
$digest(this)
},
handleImagePreview(e) {
const idx = e.target.dataset.idx
const images = this.data.images
wx.previewImage({
current: images[idx],
urls: images,
})
},
statustap:function(e){
this.setData({
coverstatus: e.detail
})
},
chooseImage(e) {
wx.chooseImage({
count: 9,
sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
success: res => {
const images = this.data.images.concat(res.tempFilePaths)
// 限制最多只能留下9张照片
this.data.images = images.length <= 9 ? images : images.slice(0, 9)
$digest(this)
}
})
},
submitForm(e) {
var self = this;
self.orderMeeting();
var clock = self.data.clock;
var coverstatus = self.data.coverstatus;
if (clock) {
wx.showToast({
title: '已打卡',
});
coverstatus = false;
}
else {
clock = true;
coverstatus = true;
}
self.setData({
clock: clock,
coverstatus: coverstatus
});
const title = self.data.title
const content = self.data.content
if (title && content) {
const arr = []
//将选择的图片组成一个Promise数组,准备进行并行上传
for (let path of this.data.images) {
arr.push(wxUploadFile({
url: config.urls.question + '/image/upload',
filePath: path,
name: 'qimg',
}))
}
wx.showLoading({
title: '正在创建...',
mask: true
})
// 开始并行上传图片
Promise.all(arr).then(res => {
console.log(222,res)
// 上传成功,获取这些图片在服务器上的地址,组成一个数组
return res.map(item => JSON.parse(item.data).url)
}).catch(err => {
console.log(">>>> upload images error:", err)
}).then(urls => {
// 调用保存问题的后端接口
return createQuestion({
title: title,
content: content,
images: urls
})
}).then(res => {
// 保存问题成功,返回上一页(通常是一个问题列表页)
const pages = getCurrentPages();
const currPage = pages[pages.length - 1];
const prevPage = pages[pages.length - 2];
// 将新创建的问题,添加到前一页(问题列表页)第一行
prevPage.data.questions.unshift(res)
$digest(prevPage)
wx.navigateBack()
}).catch(err => {
console.log(">>>> create question error:", err)
}).then(() => {
wx.hideLoading()
})
}
}
同时上传多张图片就实现啦