微信小程式上傳圖片 語音至七牛雲
阿新 • • 發佈:2018-12-22
將本地資源上傳到伺服器。客戶端發起一個 HTTPS POST 請求,其中 content-type
為 multipart/form-data
。
以上傳圖片為例
示例程式碼:
wx.chooseImage({ success(res) { const tempFilePaths = res.tempFilePaths wx.uploadFile({ url: 'https://example.weixin.qq.com/upload', // 僅為示例,非真實的介面地址 filePath: tempFilePaths[0], name: 'file', formData: { user: 'test' }, success(res) { const data = res.data // do something } }) } })
後臺介面處理接受資料
//圖片上傳七牛雲介面 public function UploadFile(){ $param = request()->param(); $file=request()->file('file'); $controller='index'; $accKey='you key'; $secret='you sercret'; $space='qqcard'; $do='10088.cn'; $img = new Upload(); $url = $img->uploadImg($file,$controller,$accKey,$secret,$space,$do); $filePath = $image->getRealPath(); return json(['url'=>$url]); }
七牛雲封裝上傳類
namespace Qiniu; require_once 'autoload.php'; use Qiniu\Auth as Auth; use Qiniu\Storage\BucketManager; use Qiniu\Storage\UploadManager; class Upload { /** * 七牛雲圖片上傳封裝類 * @param $image //圖片名稱 * @param $controller //控制器名稱 * @param $accKey //七牛雲accessKey * @param $secret //七牛雲secretKey * @param $space //七牛雲上傳空間 * @param $do //七牛雲空間繫結的域名 * @return array|string //1.成功返回圖片儲存的全路徑;2.返回錯誤資訊 */ public function uploadImg($image,$controller,$accKey,$secret,$space,$do){ $file = $image; // 要上傳圖片的本地路徑 $filePath = $file->getRealPath(); $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION); //字尾 //獲取當前控制器名稱 $controllerName = $controller; // 上傳到七牛後儲存的檔名 $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext; // 需要填寫你的 Access Key 和 Secret Key $accessKey = $accKey; $secretKey = $secret; // 構建鑑權物件 $auth = new Auth($accessKey, $secretKey); // 要上傳的空間 $bucket = $space; $domain = $do; $token = $auth->uploadToken($bucket); // 初始化 UploadManager 物件並進行檔案的上傳 $uploadMgr = new UploadManager(); // 呼叫 UploadManager 的 putFile 方法進行檔案的上傳 list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath); if ($err !== null) { return ["err"=>1,"msg"=>$err]; } else { //返回圖片的完整URL return "http://"."{$do}"."/".$key; } } }