測試需要根據空間更改region與token .
注意:
因為js是分片上傳,每個片上傳都要攜帶token,檢查token有效期,一旦過期,后續片 塊上傳直接失敗 . 所以還需要到生成token的sdk中修改有效期,默認是3600s
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>進度條屬性上傳</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input name="key" type="hidden" value=""/>
<input name="token" type="hidden" value=""/>
<input name="accept" type="hidden" />
<input id="input-file" class="upload" type="file" value="" onchange="getPhoto(this)">
<br/>
<span class="img"> </span>
<div id="totalBar" style="float:left;width:20%;height:30px;border:1px solid;border-radius:3px">
<div id="totalBarColor" style="width:0%;border:0;background:#FFFE33; color: #FFF;height:28px;"></div>
<span class="speed"></span>
</div>
<br/>
<BR/>
<input type="button" value="上傳" onclick="upload()"/>
<input type="button" value="暫停" onclick="filepause()"/>
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://unpkg.com/qiniu-js@2.5.4/dist/qiniu.min.js"></script>
<script>
var subObject;
var file;
//定義上傳配置,注意上傳域名的設置,華東空間z0,華南z2,華北z1
var config = {
region: qiniu.region.z0
};
//定義putExtra上傳限制,只可以上傳圖片
var putExtra = {
params: { 'x:name': 'qiniu'},
};
var compareChunks = [];
var observable;
var subscription;
function getPhoto(node) {
var imgURL = "";
try{
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);
}
}catch(e){
}
creatImg(imgURL,file.name);
return imgURL;
}
function creatImg(imgRUL,fileName){
$("input[name=key]").val(fileName);
//var textHtml = "<img src='"+imgRUL+"'width='40px' height='40px'/>";
//$(".img").html(textHtml);
$("#totalBarColor").css("width","0%");
}
function upload() {
// 設置next,error,complete對應的操作,分別處理相應的進度信息,錯誤信息,以及完成后的操作
subObject = {
next: next,
error: error,
complete: complete
};
token = "WuyN2MDHDJXHJDHSAJ16WICjYKpvycZmugQtCkL:xLRewO4tl9BLDJ1geunLPub6j5Q=:eyJzY2JHJHJ432432JHJ3GluZSI6MTYyMDQ0NTAxMn0="
//上傳
observable = qiniu.upload(file, file.name, token, putExtra, config);
// 調用sdk上傳接口獲得相應的observable,控制上傳和暫停
subscription = observable.subscribe(subObject);
}
function filepause(){
subscription.unsubscribe();
}
//分片上傳返回response,標記上傳進度
var next = function(response) {
var chunks = response.chunks||[];
var total = response.total;
$(".speed").text("進度:" + total.percent + "% ");
$("#totalBarColor")
.css(
"width",
total.percent + "%"
);
compareChunks = chunks;
};
var error = function(err) {
alert(err.message);
};
var complete = function(res) {
console.log(res);
console.log(res.key);
};
</script>
</body>
</html>
