基于小程序·云開發(fā)HTTP API構(gòu)建小程序的后臺內(nèi)容管理系統(tǒng)的相關技術(shù)文章連載。本文章主要介紹:基于HTTP API實現(xiàn)圖片上傳功能。
基于HTTP API實現(xiàn)內(nèi)容管理的圖片上傳功能
目前基于小程序·云開發(fā)可以快速的實現(xiàn)無服務器的小程序快速開發(fā)永高。但是小程序開發(fā)工具自帶的管理工具蔬胯,并不方便進行內(nèi)容管理春畔。因此為了更高效的管理小程序狈邑,需要開發(fā)后臺管理工具,以方便在電腦端進行內(nèi)容管理碘菜“简冢基- 于此,會陸續(xù)連載更新基于小程序·云開發(fā)HTTP API進行后臺管理工具相關開發(fā)的一些經(jīng)驗文章忍啸。
- 前端:Element-admin
- 后端:Node.js koa
前端使用element-ui el-upload組件實現(xiàn)上傳功能
- 對于element-admin以及element-ui不熟悉的請自行去官網(wǎng)學習仰坦。
- element-admin是基于element-ui組件構(gòu)建的后臺管理系統(tǒng)UI,功能強大计雌,方便快速構(gòu)建后臺管理系統(tǒng)悄晃。
Element-admin:https://panjiachen.github.io/vue-element-admin-site/zh/
Element-ui:https://element.eleme.io/#/zh-CN
<template>
<div class="dashboard-container">
<div>
<el-upload
class="upload-demo"
action="http://localhost:3000/upload/imgs"
:before-upload="beforeUploadFile"
>
<el-button size="small" type="primary">點擊上傳</el-button>
<div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過500kb</div>
</el-upload>
</div>
</div>
</template>
后端基于node koa的后端圖片上傳功能代碼
學習技術(shù)的最好方法就是官方文檔,因此要想熟練的使用HTTP API構(gòu)建小程序的后端管理系統(tǒng)妈橄,就必須先熟悉官方文檔庶近。
1.要想使用Httpapi去實現(xiàn)圖片上傳功能,我們需要先獲取訪問請求中的參數(shù)access_token眷蚓。access_token獲取的官方文檔內(nèi)容鼻种。
通過官方文檔可知,傳遞參數(shù)appid和secret沙热,發(fā)送請求到文檔中的地址叉钥,可以獲取access_token數(shù)據(jù)access_token獲取,存儲以及定時更新的相關代碼如下:
const rp = require('request-promise')
const fs = require('fs') //引用文件操作函數(shù)
const path = require('path') //引入文件路徑函數(shù)
//獲取文件的絕對路徑
const filePath = path.resolve(__dirname, './access_token.json')
//小程序的APPID和Secret
const APPID = '小程序的APPID'
const Secret = '小程序的Secret'
//獲取Token的URL
const URL = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${Secret}`
//從小程序端獲取Token函數(shù)
const updateAccessToken = async () => {
const resStr = await rp(URL)
//將字符串類型轉(zhuǎn)為對象
const res = JSON.parse(resStr)
if (res.access_token) {
//寫入文件
fs.writeFileSync(filePath, JSON.stringify({
access_token: res.access_token, //從小程序服務器獲取的token
createTime: new Date() //獲取token時篙贸,對應的時間
}))
} else { //如果文件不存在投队,則重新調(diào)用獲取token函數(shù),重新執(zhí)行寫入
await updateAccessToken()
}
}
//查詢Token函數(shù)返回給響應的函數(shù)去調(diào)用云函數(shù)
const getAccessToken = async () => {
try {
//讀取文件
const readRes = fs.readFileSync(filePath, 'utf8')
const readObj = JSON.parse(readRes)
//獲取access_token.json中的createtime的時間
const createTime = new Date(readObj.createTime).getTime()
//獲取當前時間
const nowTime = new Date().getTime()
//判斷Token的失效是否大于2小時爵川,如果大于2小時則需要重新獲取Token,然后在讀取Token數(shù)據(jù)
if ((nowTime - createTime) / 1000 / 60 / 60 >= 2) {
await updateAccessToken()
await getAccessToken()
}
//返回Token數(shù)據(jù)
return readObj.access_token
} catch (error) { //如果access_token文件不存在敷鸦,則讀取報錯,此時需要重新從服務器獲取token數(shù)據(jù)寝贡,再讀取token數(shù)據(jù)
await updateAccessToken()
await getAccessToken()
}
}
//定時更新Token
setInterval(async () => {
await updateAccessToken()
}, (7200 - 300) * 1000)
module.exports = getAccessToken;
2.獲取文件上傳鏈接
從官方文檔可知轧膘,傳遞access_token和env參數(shù),訪問文檔中的請求地址兔甘,獲取上傳文件所需的參數(shù)數(shù)據(jù)。
從官方文檔可知鳞滨,返回的上傳數(shù)據(jù)中包含如下內(nèi)容:
- authorization字段
- token字段
- cos_file_id字段
- url字段
3.上傳文件到云存儲
按照官方文檔洞焙,訪問返回的url字段的鏈接,并傳遞相關參數(shù)拯啦,將圖片上傳到云存儲澡匪。
圖片上傳功能的代碼如下:
const rp = require('request-promise')
const fs = require('fs') //引用文件操作函數(shù)
const getAccessToken = require('./getAccessToken')
const cloudStorage = {
// 1、請求地址
async upload(ctx){
console.log(1,ctx)
const ACCESS_TOKEN = await getAccessToken()
const file = ctx.request.files.file
const path = `test/${Date.now()}-${Math.random()}-${file.name}`
var options = {
method: 'POST',
uri: `https://api.weixin.qq.com/tcb/uploadfile?access_token=${ACCESS_TOKEN}`,
body: {
env: 'miniprogram-dev-y7a0a',
path,
},
json: true // Automatically stringifies the body to JSON
};
//請求返回的參數(shù)
const info = await rp(options)
.then(res => {
// POST succeeded...
return res
})
.catch(err => {
// POST failed...
console.log(err)
});
// 2褒链、上傳文件到云存儲
const params ={
method: 'POST',
uri:info.url,
header:{
'content-type':'multipart/form-data'
},
formData:{
key:path,
Signature:info.authorization,
'x-cos-security-token':info.token,
'x-cos-meta-fileid':info.cos_file_id,
file:fs.createReadStream(file.path)
},
json: true // Automatically stringifies the body to JSON
}
await rp(params)
return info.file_id
}
}
module.exports=cloudStorage;
歡迎大家關注我唁情,后續(xù)會陸續(xù)更新相關技術(shù)文章,來幫助大家快速熟悉和使用小程序·云開發(fā)實現(xiàn)小程序的快速開發(fā)甫匹,以及基于HTTP API實現(xiàn)小程序后端管理系統(tǒng)的開發(fā)甸鸟。
轉(zhuǎn)載請注明出處,否則一經(jīng)發(fā)現(xiàn)兵迅,違者必究抢韭。