我小程序项目是用原生微信开发者工具开发,但是迫于微信云收费,只得又转到阿里云上,用unicloud开发后台。项目中遇到上传文章图片到unicloud云存储,查阅半天官方文档没有详细教程,最终功夫不负有心人摸索成功。
一、页面js代码
chooseimg() {
wx.chooseMedia({ //小程序官方已经弃用了wx.chooseImage
count: 9,
mediaType: ["image"],
sourceType: ["album", "camera"],
sizeType: ["compressed"]
}).then(res => {
this.data.tempimgarr.push(...res.tempFiles)
this.setData({
tempimgarr: this.data.tempimgarr //获取到临时图片地址数组,用于上传
})
})
},
submit() {
if (this.data.tempimgarr.length > 0) {
uploadfile(this.data.tempimgarr).then(res => {
//上传成功插入到数据库中
let insertObj = {
userid: xxx,
datetime: Date.now(),
status: 0,
imgarr: res,
message: this.data.content
}
insertBaoxiu(insertObj).then(res2 => {
console.log(res2)
})
})
}
},
二、自定义fileAPI接口
import httprequest from "../utils/httprequest"
export const uploadfile = (tempfilearr) => {
const fs = wx.getFileSystemManager()
return Promise.all(tempfilearr.map(item => { //封装promise可以一次传多张图片
return new Promise((resolve, reject) => {
fs.readFile({
filePath: item.tempFilePath,
encoding: "base64",
success(res) {
httprequest("/fileapi/uploadFile", { //自己对wx.request进行promise封装
method: "POST",
data: {
filename: Date.now() + item.tempFilePath.substring(item.tempFilePath.lastIndexOf(".")),
filebuffer: res.data
}
}).then(res2 => {
resolve(res2)
}).catch(err2 => {
reject(err2)
})
},
fail(err) {
reject(err)
}
})
})
}))
三、对wx.request进行promise封装
const baseUrl = "https://xxx" //unicloud云对象的调用地址
export default function request(url, params = {}) {
return new Promise((resolve, reject) => {
wx.showLoading({
title: '加载中...',
})
wx.request({
url: baseUrl + url,
data: params.data || {},
header: params.header || {},
method: params.method || "GET",
dataType: "json",
success: res => {
wx.hideLoading()
resolve(res.data)
},
fail: err => {
wx.hideLoading()
wx.showToast({
title: err || "请求错误",
})
reject(err)
}
})
})
}
四、至此微信端完毕,开发uncloud接口端fileAPI云对象
module.exports = {
_before: function() { // 通用预处理器
this.params = JSON.parse(this.getHttpInfo().body)
},
uploadFile() {
return uniCloud.uploadFile({
cloudPath: this.params.filename,
fileContent: Buffer.from(this.params.filebuffer, "base64")
})
}
}