因爲要從雲儲存調用圖片,對輪播圖進行設置
所以前期工作要做足,首先在雲控制檯的雲存儲中新建一個文件banner
來存放圖片
新建數據庫banner
來存放圖片信息
獲取數據信息,下載文件展示輪播圖
在前端中獲取顯示列表信息的方法,在生命週期函數中響應
在前端請求數據
// 獲取輪播圖列表信息
export function fetchList() {
// 發送請求
return request({
url: `${baseUrl}/banner/list`,
method: 'get'
})
}
後端和之前的方法一樣,集成一個雲存儲的工具類,方便調用。
const getAccessToken = require('./getAccessToken.js')
const rp = require('request-promise')
const cloudStorage = {
async download(ctx,fileList){
const ACCESS_TOKEN = await getAccessToken()
const options = {
method: 'POST',
uri: `https://api.weixin.qq.com/tcb/batchdownloadfile?access_token=${ACCESS_TOKEN}`,
body: {
env: ctx.state.env,
file_list:fileList
},
json: true // Automatically stringifies the body to JSON
}
return await rp(options)
.then((res) => {
return res
})
.catch(function (err) {
console.log(err)
})
}
}
module.exports = cloudStorage
調用時,因爲雲存儲與雲數據庫還有一點點不一樣,爲了在網頁中進行查看,是需要將返回的fileID進行轉換爲網頁可以使用的格式。然後將我們的獲取到的需要數據,返回到前端中
router.get('/list',async(ctx,next)=>{
//默認讀取10條數據(查詢數據庫)
const query=`db.collection('banner').get()`
const res=await callCloudDB(ctx,'databasequery',query)
//因爲存儲的fileID無法在網頁中直接調用,所以調用文件下載的鏈接轉化fileID
let fileList = []
const data = res.data
for(let i=0,len=data.length; i<len; i++){
fileList.push({
fileid: JSON.parse(data[i]).fileid,
max_age: 7200
})
}
const downres = await cloudStorage.download(ctx,fileList) //循環遍歷輸出下載鏈接內容
//返回前端所有要使用的值
let returnData = []
for(let i=0,len=downres.file_list.length;i<len;i++){
returnData.push({
download_url:downres.file_list[i].download_url,
fileid:downres.file_list[i].fileid,
_id: JSON.parse(data[i])._id
})
}
ctx.body = {
code:20000,
data:returnData
}
})