在小程序云開發(fā)中,要實現(xiàn)上傳文件至云存儲韩脑,有兩種方案:云函數(shù)和HTTP API谆奥,前者是在小程序內(nèi)調(diào)用的,而后者則是在小程序外調(diào)用的菇肃。本文主要講講如何使用HTTP API實現(xiàn)小程序外上傳文件至云存儲地粪。
一、原料
① 小程序HTTP API
② PHP
③ Vue.js + Element UI
HTTP API需要在服務(wù)器端發(fā)起調(diào)用琐谤,而這里我選擇的后端語言是PHP蟆技。
Element UI只是作為前端舉例,我們可以用它的Upload組件來上傳文件斗忌,如果是原生上傳則直接用input file即可质礼。
二、PHP調(diào)用小程序HTTP API
// 獲取access_token
function getAccessToken(){
// APPID和SECRET均可在小程序后臺獲取
$appid = 'APPID';
$secret = 'SECRET';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".
$appid ."&secret=". $secret;
$res = curl_get($url); // 使用GET方式請求微信接口
$res = json_decode($res,1);
return $res['access_token'];
}
// 上傳文件到小程序云存儲
function upload(){
$path = $_REQUEST['path'];
$url = "https://api.weixin.qq.com/tcb/uploadfile?access_token=". getAccessToken();
$data = array ('path' => $path,'env' => APP_CLOUD_ID); // APP_CLOUD_ID是你小程序的云環(huán)境ID
$res = json_decode(request($url, $data),1);
$fileName = $_FILES['file']['tmp_name'];
$handle = fopen($fileName,"r");
$file = fread($handle,filesize($fileName));
curl_post(
$res['url'],
array (
'key' => $path,
'Signature' => $res['authorization'],
'x-cos-security-token' => $res['token'],
'x-cos-meta-fileid' => $res['cos_file_id'],
'file' => $file,
)
);
echo json_encode(array(
'code' => 200,
'msg' => '文件上傳成功',
'data' => $res['file_id']
));
}
// get請求
function curl_get($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
return curl_exec($ch);
curl_close($ch);
}
// post請求
function curl_post($url, $data){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
return curl_exec($ch);
curl_close($ch);
}
有關(guān)文件上傳的HTTP API具體用法可參考:獲取文件上傳鏈接
三飞蹂、使用Element UI調(diào)用PHP接口
// VueJS
<template>
<el-upload
class="avatar-uploader"
:action=""
accept="image/*,.jpg"
:http-request="upload"
:show-file-list="false"
>
<img v-if="image" :src="image" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</template>
<script>
import axios from 'axios'
const request = axios.create({
baseURL: process.env.BASE_API, // api 的 base_url
timeout: 20000
});
export default {
data() {
return {
image: ''
};
},
methods: {
async upload(e) {
let formData = new FormData();
let path = `upload/${new Date().getTime() + e.file.name.match(/\.(.*)/)[0]}`;
formData.append("path", path);
formData.append("file", e.file);
await request({
url: '/api/upload', // php提供的上傳接口
method: 'post',
headers: {
"Content-Type": "multipart/form-data",//設(shè)置headers
},
data: formData
});
this.image = '【小程序云存儲域名】' + path;
}
};
</script>
結(jié)束語
以上僅僅只是最近項目的摘錄和總結(jié)几苍,由于涉及到一些項目隱私,所以代碼并不是特別完整陈哑,但大體思路就是如此妻坝,已通過實踐檢驗可行,希望對一些正好有此需求的朋友有所幫助惊窖!