七牛雲實現表單上傳
阿新 • • 發佈:2018-11-08
表單上傳適用於檔案內容可以在一次 HTTP 請求即可傳遞完成的場景。該功能非常適合在瀏覽器中使用 HTML 表單上傳資源,或者在不需要處理複雜情況的客戶端開發中使用。如果檔案較大(大於 1GB),或者網路環境較差,可能會導致 HTTP 連線超時而上傳失敗。若發生這種情況,您需要考慮換用更安全的分片上傳功能。
開發者只要組裝一個符合 HTML 檔案上傳表單規範(參考RFC1867)的 HTTP 請求,並以 POST 方式向域名 upload.qiniu.com 發起這個請求,即可將指定檔案上傳到服務端。詳細使用方法請參考表單上傳 API。
使用方法
我們可以用如下的 HTML 表單來描述表單上傳的基本用法:
<form method="post" action="http://upload.qiniup.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="crc32" type="hidden" /> <input name="accept" type="hidden" /> <input name="file" type="file" /> <input type="submit" value="上傳檔案" /> </form>
關鍵引數說明:
名稱 | 型別 | 必填 | 說明 | |
---|---|---|---|---|
action | string | 是 | 上傳地址,可參考儲存區域 | |
resource_key | string | 否 | 資源名,必須是 UTF-8 編碼。注意: 如果上傳憑證中 scope 指定為 <bucket>:<key>, 則該欄位也必須指定。 | |
custom_name | string | 否 | 自定義變數 |
|
custom_value | string | 否 | 自定義變數的值。 | |
upload_token | string | 是 | 必須是一個符合相應規格的上傳憑證,否則會返回 401 表示許可權認證失敗。 | |
crc32 | string | 否 | 上傳內容的 crc32 校驗碼。如填入,則七牛伺服器會使用此值進行內容檢驗。 | |
accept | string | 否 | 當 HTTP 請求指定 accept 頭部時,七牛會返回 content-type 頭部的值。該值用於相容低版本 IE 瀏覽器行為。低版本 IE 瀏覽器在表單上傳時,返回 application/json 表示下載,返回 text/plain 才會顯示返回內容。 | |
file | file | 是 | 檔案本身。 |
提交示例如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表單小圖片上傳</title>
<script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script>
var imgurl = "";
function getPhoto(node) {
var imgURL = "";
try{
var file = null;
if(node.files && node.files[0] ){
file = node.files[0];
}else if(node.files && node.files.item(0)) {
file = node.files.item(0);
}
//Firefox 因安全性問題已無法直接通過input[file].value 獲取完整的檔案路徑
try{
imgURL = file.getAsDataURL();
}catch(e){
imgRUL = window.URL.createObjectURL(file);
}
}catch(e){
if (node.files && node.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
imgURL = e.target.result;
};
reader.readAsDataURL(node.files[0]);
}
}
creatImg(imgRUL,file.name);
return imgURL;
}
function creatImg(imgRUL,fileName){
console.log(fileName);
$("input[name=key]").val(fileName);
var textHtml = "<img src='"+imgRUL+"'width='40px' height='40px'/>";
$("span").html(textHtml);
}
function upload(){
document.getElementById('form1').submit();
}
</script>
</head>
<body>
<form id="form1" method="post" action="http://upload-z1.qiniup.com/"
enctype="multipart/form-data">
<input name="key" value="" type="hidden"/>
<input name="token" value="bSF1IPT5YKp729o4ietO-M-ONzNcW90snELGm3sv:iPtb7rdYOHLb7Gjsz_ifjeu_t_4=:eyJzY29wZSI6Im91dHNvdXJjZSIsImRlYWRsaW5lIjoxNTM4MDM4NzU0fQ==" type="hidden"/>
<input id="input-file" name="file" class="upload" type="file" value="" onchange="getPhoto(this)">
<input type="button" value="上傳" onclick="upload()">
</form>
<br/>
<span> </span>
</body>
</html>
參考資訊:https://developer.qiniu.com/kodo/manual/1272/form-upload