計劃用php寫一個七牛文件上傳小工具

功能

輸入框中填入:bucket   Access Key 和 Secret Key php

點擊提交後,向七牛服務器認證,若認證經過,則在當前頁面動態刷新,剛纔的輸入框消失。html

顯示一個上傳文件按鈕,點擊可繼續添加文件(最多同時上傳5個)。文件的key爲yyy-mm-dd-hh-name.xxxapi

而後提交文件後顯示進度條,並在下面動態回顯上傳文件的結果以及文件的url。安全

七牛API

上傳策略

{
    "scope":               "<Bucket                   string>",
    "deadline":             <UnixTimestamp            int64>,
    "endUser":             "<EndUserId                string>",

    "returnUrl":           "<RedirectURL              string>",
    "returnBody":          "<ResponseBodyForAppClient string>",

    "callbackBody":        "<RequestBodyForAppServer  string>",
    "callbackUrl":         "<RequestUrlForAppServer   string>",

    "persistentOps":       "<persistentOpsCmds        string>",
    "persistentNotifyUrl": "<persistentNotifyUrl      string>",

    "insertOnly":          "<AllowFileUpdating        uint16>",
    "detectMime":          "<AutoDetectMimeType       uint16>",
    "fsizeLimit":          "<FileSizeLimit            int64>",
    "saveKey":             "<KeyFomart                string>",

    "mimeLimit":           "<MimeLimit                string>"
}

其中scope和deadline爲必選。 服務器

上傳憑證

1.構造上傳策略
2.將上傳策略序列化成爲JSON格式
3.對JSON編碼的上傳策略進行URL安全的Base64編碼,獲得待簽名字符串:
encodedPutPolicy = urlsafe_base64_encode(putPolicy)
4.使用SecertKey對上一步生成的待簽名字符串計算HMAC-SHA1簽名
sign = hmac_sha1(signingStr, "<SecretKey>")
5.對簽名進行URL安全的Base64編碼:
encodedSign = urlsafe_base64_encode(sign)
6.將AccessKey、encodedSign和encodedPutPolicy用:鏈接起來:
uploadToken = AccessKey + ':' + encodedSign + ':' + encodedPutPolicy

表單上傳(POST方式)

<form method="post" action="http://up.qiniu.com/"
 enctype="multipart/form-data">
  <input name="key" type="hidden" value="<resource_key>">
  <input name="x:<custom_name>" type="hidden" value="<custom_value>">
  <input name="token" type="hidden" value="<upload_token>">
  <input name="file" type="file" />
</form>

token和file爲必選,token指的是上傳憑證,file爲文件自己post

反饋

PHP實現

服務端生成上傳憑證

require_once("qiniu/rs.php");

$bucket = 'phpsdk';
$accessKey = '<YOUR_APP_ACCESS_KEY>';
$secretKey = '<YOUR_APP_SECRET_KEY>';

Qiniu_SetKeys($accessKey, $secretKey);
$putPolicy = new Qiniu_RS_PutPolicy($bucket);
$upToken = $putPolicy->Token(null);

上傳本地文件

require_once("qiniu/io.php");
require_once("qiniu/rs.php");

$bucket = "phpsdk";
$key1 = "file_name1";
$accessKey = '<YOUR_APP_ACCESS_KEY>';
$secretKey = '<YOUR_APP_SECRET_KEY>';

Qiniu_SetKeys($accessKey, $secretKey);
$putPolicy = new Qiniu_RS_PutPolicy($bucket);
$upToken = $putPolicy->Token(null);
$putExtra = new Qiniu_PutExtra();
$putExtra->Crc32 = 1;
list($ret, $err) = Qiniu_PutFile($upToken, $key1, __file__, $putExtra);
echo "====> Qiniu_PutFile result: \n";
if ($err !== null) {
    var_dump($err);
} else {
    var_dump($ret);
}

參考

  • [1]:http://developer.qiniu.com/docs/v6/api/reference/security/upload-token.htmlui

  • [2]:http://developer.qiniu.com/docs/v6/api/reference/security/put-policy.html編碼

相關文章
相關標籤/搜索