1 先下載源碼php
點擊下載git
https://github.com/tencentyun/cos-php-sdk-v5/releases/download/v2.0.8/cos-sdk-v5.tar.gzgithub
有vendor文件夾的服務器
2解壓後再 當前目錄新建了個upload.phpcurl
3 測試可上傳 文件以下post
<?php function cos_file_upload($local_path,$server_key_name) { require dirname(__FILE__) . '/vendor/autoload.php'; $secretId = "111"; //"雲 API 密鑰 SecretId"; $secretKey = "222"; //"雲 API 密鑰 SecretKey";改爲本身的 $region = "ap-nanjing"; //設置一個默認的存儲桶地域 $cosClient = new Qcloud\Cos\Client( array( 'region' => $region, 'schema' => 'https', //協議頭部,默認爲http 'credentials'=> array( 'secretId' => $secretId , 'secretKey' => $secretKey))); //定義數據 $upload_success = false; $img_url = ''; $upload_msg = ''; try { $result = $cosClient->upload( $bucket = '1222', //請建立桶的時候 設置公共讀寫 改爲本身的 $key = $server_key_name, $body = fopen($local_path, 'rb') ); // 請求成功 $data = $result->toArray() ; if(isset($data['Location']) && isset($data['Key'])){ $img_url = $data['Location']; $upload_success = true; } } catch (\Exception $e) { // 請求失敗 $upload_msg = $e->getMessage(); } //返回信息 if($upload_success){ return array('id' => '0001','msg' => '上傳成功','info'=>$img_url,'more'=>''); } else{ return array('id' => '0002','msg' => '上傳失敗','info'=>$upload_msg);//返回‘上傳失敗’,並返回錯誤信息 } } if($_POST) { $local_path=$_FILES['file']['tmp_name'];//文件上傳後的臨時目錄 $server_key_name="123.jpg";//遠程服務器存儲的名字 $res=cos_file_upload($local_path,$server_key_name); var_dump($res);exit; } else { ?> <form enctype="multipart/form-data" method="post" action="upload.php" > <input type="file" name="file" id ="file" class ="up-file" style="height:34px;width:600px;margin-left:-8px;border:1px solid #ccc"> <input type="hidden" name="aa" id="aa" value=0> <input type="submit" id = 'btn' value = "提交" class = "btn"> </form> <?php } ?>
幾個注意的地方測試
1)通過測試目前只支持https的站點上傳 不是https的會報錯ui
curl error 60 url
2) 桶至關於文件夾 就是把文件放到哪一個文件夾spa
桶能夠設置 各類權限 設置爲公有 就能夠上傳後 而後直接訪問
3)關於API祕鑰