uploadWithSDK.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. function uploadWithSDK(token, putExtra, config, domain) {
  2. // 切换tab后进行一些css操作
  3. controlTabDisplay("sdk");
  4. $("#select2").unbind("change").bind("change",function(){
  5. var file = this.files[0];
  6. // eslint-disable-next-line
  7. var finishedAttr = [];
  8. // eslint-disable-next-line
  9. var compareChunks = [];
  10. var observable;
  11. if (file) {
  12. var key = file.name;
  13. // 添加上传dom面板
  14. var board = addUploadBoard(file, config, key, "");
  15. if (!board) {
  16. return;
  17. }
  18. putExtra.customVars["x:name"] = key.split(".")[0];
  19. board.start = true;
  20. var dom_total = $(board)
  21. .find("#totalBar")
  22. .children("#totalBarColor");
  23. // 设置next,error,complete对应的操作,分别处理相应的进度信息,错误信息,以及完成后的操作
  24. var error = function(err) {
  25. board.start = true;
  26. $(board).find(".control-upload").text("继续上传");
  27. console.log(err);
  28. alert("上传出错")
  29. };
  30. var complete = function(res) {
  31. $(board)
  32. .find("#totalBar")
  33. .addClass("hide");
  34. $(board)
  35. .find(".control-container")
  36. .html(
  37. "<p><strong>Hash:</strong>" +
  38. res.hash +
  39. "</p>" +
  40. "<p><strong>Bucket:</strong>" +
  41. res.bucket +
  42. "</p>"
  43. );
  44. if (res.key && res.key.match(/\.(jpg|jpeg|png|gif)$/)) {
  45. imageDeal(board, res.key, domain);
  46. }
  47. };
  48. var next = function(response) {
  49. var chunks = response.chunks||[];
  50. var total = response.total;
  51. // 这里对每个chunk更新进度,并记录已经更新好的避免重复更新,同时对未开始更新的跳过
  52. for (var i = 0; i < chunks.length; i++) {
  53. if (chunks[i].percent === 0 || finishedAttr[i]){
  54. continue;
  55. }
  56. if (compareChunks[i].percent === chunks[i].percent){
  57. continue;
  58. }
  59. if (chunks[i].percent === 100){
  60. finishedAttr[i] = true;
  61. }
  62. $(board)
  63. .find(".fragment-group li")
  64. .eq(i)
  65. .find("#childBarColor")
  66. .css(
  67. "width",
  68. chunks[i].percent + "%"
  69. );
  70. }
  71. $(board)
  72. .find(".speed")
  73. .text("进度:" + total.percent + "% ");
  74. dom_total.css(
  75. "width",
  76. total.percent + "%"
  77. );
  78. compareChunks = chunks;
  79. };
  80. var subObject = {
  81. next: next,
  82. error: error,
  83. complete: complete
  84. };
  85. var subscription;
  86. // 调用sdk上传接口获得相应的observable,控制上传和暂停
  87. observable = qiniu.upload(file, key, token, putExtra, config);
  88. $(board)
  89. .find(".control-upload")
  90. .on("click", function() {
  91. if(board.start){
  92. $(this).text("暂停上传");
  93. board.start = false;
  94. subscription = observable.subscribe(subObject);
  95. }else{
  96. board.start = true;
  97. $(this).text("继续上传");
  98. subscription.unsubscribe();
  99. }
  100. });
  101. }
  102. })
  103. }