在小程序云开发中,要实现上传文件至云存储,有两种方案:云函数和HTTP API,前者是在小程序内调用的,而后者则是在小程序外调用的。本文主要讲讲如何使用HTTP API实现小程序外上传文件至云存储。
一、原料
① 小程序HTTP API
② PHP
③ Vue.js + Element UI
HTTP API需要在服务器端发起调用,而这里我选择的后端语言是PHP。
Element UI只是作为前端举例,我们可以用它的Upload组件来上传文件,如果是原生上传则直接用input file即可。
二、PHP调用小程序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是你小程序的云环境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);
- }
有关文件上传的HTTP API具体用法可参考:获取文件上传链接
三、使用Element UI调用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",//设置headers
- ? ? ? ? },
- ? ? ? ? data: formData
- ? ? ? });
- ? ? ? this.image = '【小程序云存储域名】' + path;
- ? ? }
- };
- </script>
结束语
以上仅仅只是最近项目的摘录和总结,由于涉及到一些项目隐私,所以代码并不是特别完整,但大体思路就是如此,已通过实践检验可行,希望对一些正好有此需求的朋友有所帮助!
到此这篇关于小程序外上传文件至云存储的实现的文章就介绍到这了,更多相关小程序外上传文件至云存储内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!