upload.js 19.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
/**
 * 封装文件上传插件
 * showprocess:是否展示进度条 | Boolean | 默认true
 * action:上传接口 | tring类型 | 非必填
 * tips: 上传文件说明 | String类型 或者 Number类型 | 非必填
 * size: 大文件分割切片大小 | Number类型 | 默认为2M
 * success: 文件上传成功回调 | Function | 非必填
 * error:文件上传失败回调 | Function | 非必填
 * accept:支持上传文件格式 | Array类型 | 非必填
 * max: 限制上传文件大小 | Number类型 | 非必填 | 单位为M
 * data: 额外上传的参数 | Object类型 | 非必填
 * beforeUpload: 上传之前校验 | Function | 非必填
 */
import MD5 from 'md5'
var that = ''
var w = {}
var upload = function(options) {
  //upload("options") 或者 new upload("options")都可以使用upload方法
  if (!(this instanceof upload)) {
    return new upload(options)
  }

  // 参数合并 extend方法体在下面
  this.options = this.extend(
    {
      showprocess: true,
      action: '',
      tips: '',
      size: 2,
      url: '',
      success: ''
    },
    options
  )

  // 基本公用的配置
  this.config = {
    id: '',
    token: '',
    app_key: '48e5e13229b82c1b4e6e8c96151f0637',
    v: '1.0.0',
    format: 'json',
    url: 'http://didicb.glsx.com.cn/router',
    secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
  }

  /*this.token = '';
        this.app_key = '48e5e13229b82c1b4e6e8c96151f0637';
        this.v = '1.0.0';
        this.format = 'json';
        this.url = 'http://qcdidicb.glsx.net:7060/router';
        this.secret = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b';*/

  //初始化
  //this.init();
  that = this
}

upload.prototype = {
  /**
   * 初始化方法
   */
  init: function(id) {
    if (!id) {
      return false
    }

    var o = that.options

    that.config.id = id

    console.log(that.config)

    //创建最外层div
    var _div = document.createElement('div')
    _div.className = 'test'
    _div.style = 'position:relative;'

    //创建按钮div
    var _iptdiv = document.createElement('div')
    _iptdiv.className = 'upload_button_box'
    _iptdiv.style = 'position:relative;'

    //创建选择文件input
    var _input = document.createElement('input')
    _input.type = 'file'
    _input.className = 'file_input'
    _input.style = 'opacity:0;position:absolute;top:0px;right:0px;bottom:0px;left:0px;font-size:14px;'
    _input.onchange = this.clickEvent
    _iptdiv.appendChild(_input)

    //创建按钮
    var _button = document.createElement('button')
    _button.className = 'testbu'
    _button.innerText = '选择文件'
    _button.style = 'border:1px solid #409eff;background:#409eff;color:#fff;border-radius:4px;padding:6px 14px;outline:none;font-size:14px;'
    _iptdiv.appendChild(_button)
    _div.appendChild(_iptdiv)

    //创建文件展示区域
    var _fileDiv = document.createElement('div')
    _fileDiv.className = 'upload_file_show_box'
    _fileDiv.id = 'upload_file_show_box'
    _fileDiv.style = 'position:absolute;left:0px;font-size:12px;color:#999;'

    //创建提示语
    if (o.tips) {
      var _tipsDiv = document.createElement('div')
      _tipsDiv.innerText = o.tips
      _tipsDiv.style = 'font-size:12px;color:#999;line-height:2;'
      _fileDiv.appendChild(_tipsDiv)
    }

    //创建file文件名展示
    var _fileNameDiv = document.createElement('div')
    _fileNameDiv.id = 'upload_file_name_box'
    _fileNameDiv.style = 'color:#333;line-height:2;'
    _fileDiv.appendChild(_fileNameDiv)

    _div.appendChild(_fileDiv)

    if (o.showprocess) {
      //创建进度条
      var _pDiv = document.createElement('div')
      _pDiv.className = 'progress_box'
      _pDiv.id = 'upload_progress_box'
      _pDiv.style = 'background:#ebeef5;border-radius:100px;position:relative;height:2px;min-width:200px;display:none;'

      //创建进度条内部
      var _iDiv = document.createElement('div')
      _iDiv.className = 'progress_box_inner'
      _iDiv.style = 'background:#409eff;border-radius:2px;position:absolute;left:0px;top:0px;bottom:0px;border-radius:100px;'
      _pDiv.appendChild(_iDiv)
      _fileDiv.appendChild(_pDiv)
    }

    var _obj = document.querySelector('#' + id)
    _obj.appendChild(_div)
  },

  // 参数合并方法体
  extend: function(obj, obj2) {
    for (var key in obj2) {
      obj[key] = obj2[key]
      //    确保参数唯一
    }
    return obj
  },

  /**
   * 监听文件变化
   */
  // clickEvent: function(e) {
  //   var files = document.querySelector('#' + that.config.id + ' input.file_input').files
  //   console.log(files[0])
  //   if (!files || files.length <= 0) {
  //     return false
  //   }
  //   that.checkFile(files[0])
  // },
  clickEvent: function(e) {
    var files = e
    if (!files || files.length <= 0) {
      return false
    }
    that.checkFile(files[0])
  },
  /**
   * 处理选中的文件
   */
  treatEvent: async function(file) {
    //var random = Math.random();
    // var _workerJs = await that.calculateHashWorker()
    // var _workerJs = that.createWorker()
    var webWorker = new Worker('/hash.js')

    // if (that.options.showprocess) {
    //   document.querySelector('#' + that.config.id + ' div#upload_file_name_box').innerText = file.name
    //   document.querySelector('#' + that.config.id + ' div#upload_progress_box') ? (document.querySelector('#' + that.config.id + ' div#upload_progress_box').style.display = 'block') : ''
    // }

    var oParams = {}
    oParams.file = file
    oParams.config = that.config
    //oParams.options = that.options;
    webWorker.postMessage(oParams)
    webWorker.onmessage = function(e) {
      console.log(e)
      var _obj = e.data
      w = _obj
      // var arr = that.fileSlice(_obj);
      // var files = arr;

      // //获取token
      var r1 = getToken(file)
      // var r1 = that.getToken(file, arr.length);
      // //获取检查文件上传情况
      // var r2 = that.checkFileIsUpload(_obj.md5);
      var _arr = fileSlice(_obj)
      w.list = _arr
      w.fileMD5 = _obj.fileMD5
      Promise.all([r1]).then(res => {
        var _token = res[0]
        that.config.token = _token
        checkFileIsUpload(_obj.fileMD5).then(res => {
          var _data = res.data
          if (res.code == 0) {
            //如果存在fileUrl,则证明服务器存在该文件
            if (_data.fileUrl) {
              _allCallback(_data.fileUrl)
              return false
            }

            send(_arr)
          }
        })
      })
    }
  },

  /**
   * 文件校验
   */
  checkFile: function(file) {
    var o = that.options
    var max = o.max ? Number(o.max) * 1024 * 1024 : ''
    if (max && file.size > max) {
      alert('文件过大')
      return false
    }

    //文件上传前回调
    if (o.beforeUpload) {
      var n = o.beforeUpload()
      if (n === false) {
        return false
      }
    }

    //

    that.treatEvent(file)
  },
  async calculateHashWorker() {
    return new Promise(resolve => {
      this.worker = new Worker('/hash.js')
      this.worker.postMessage({ chunks: this.chunks })
      this.worker.onmessage = e => {
        const { hash } = e.data
        if (hash) {
          resolve(hash)
        }
      }
    })
  }
  // //创建worker分线程
  // createWorker: function() {
  //   var myWorker = function() {
  //     let that = this
  //     let w = {}
  //     // importScripts('https://img01.glsx.com.cn/weapp/resource/file-upload/spark-md5.min.js')
  //     that.addEventListener(
  //       'message',
  //       function(e) {
  //         var _obj = e.data
  //         var files = _obj.file
  //         var spark = new SparkMD5.ArrayBuffer()
  //         var reader = new FileReader()

  //         w.config = _obj.config
  //         w.options = _obj.options
  //         w.file = _obj.file

  //         //var r1 = getToken(files);

  //         reader.readAsArrayBuffer(files)
  //         reader.onload = function(e) {
  //           console.log('加密开始:' + new Date().getTime())
  //           spark.append(e.target.result)
  //           var hexHash = spark.end()
  //           if (hexHash) {
  //             console.log('加密结束:' + new Date().getTime())
  //           }
  //           var oParams = {}
  //           oParams.fileMD5 = hexHash
  //           oParams.file = e.target.result
  //           oParams.size = files.size

  //           //w.fileMD5 = hexHash;

  //           that.postMessage(oParams)
  //           /*var _arr = fileSlice(oParams);
  //                       console.log(_arr)
  //                       w.list = _arr;
  //                       Promise.all([r1]).then(res => {
  //                           checkFileIsUpload(hexHash).then(res => {
  //                               console.log(res);
  //                               if (res.code == 0) {
  //                                   send(_arr);
  //                               }
  //                           });
  //                       })*/
  //         }
  //       },
  //       false
  //     )
  //   }

  //   var workerData = new Blob(['(' + myWorker.toString() + ')()'], {
  //     type: 'text/javascript'
  //   })
  //   return workerData
  // }
}

/**
 * 封装请求方法
 */
function request(options) {
  return new Promise(function(resolve, reject) {
    var _url = options.url
    var _data = options.data
    var xhr = new XMLHttpRequest()

    // 设置超时时间,0表示永不超时
    xhr.timeout = options.timeout || 0

    //设置返回数据类型
    xhr.responseType = options.responseType || 'json'

    //请求成功
    xhr.onload = function(res) {
      resolve(res.target.response)
    }
    //请求失败
    xhr.onerror = function(res) {
      reject(res.target.response)
    }

    //请求超时
    xhr.ontimeout = function(res) {
      reject(res.target.response)
    }

    if (options.method == 'GET' || options.method == 'get') {
      //formRequestData(options.data);
      var _str = formRequestData(_data)
      _url = _url + '?' + _str
      _data = ''
    }

    xhr.open(options.method || 'post', _url, true)

    //xhr.setRequestHeader("Content-type", options.header || "application/json");

    if (options.method == 'POST' || options.method == 'post') {
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
      //xhr.setRequestHeader("Content-type", options.header || "application/json");
      //xhr.send(JSON.stringify(_data));
      var _str_d = formRequestData(_data)
      xhr.send(_str_d)
    } else {
      xhr.send()
    }
  })
}

/**
 * 文件上传
 */
function send(arr) {
  let max = 3 //最多允许同时执行的ajax次数
  var current = 0 //当前有多少ajax正在执行
  var _name = getFileType(w.fileName)
  let _num = 0
  var len = arr.length
  var hasFile = false

  /* var _index = 0;

        while (arr[_index]) {
            current++;
            var c = arr.shift();
            var fileBase64 = transformArrayBufferToBase64(c);
            var oParams = getParams(_index, fileBase64);
            var o = {};
            oParams.file = oParams.fileType + '@' + fileBase64;

            o.method = 'POST';
            o.data = oParams;
            o.url = that.config.url + '?method=glsx.accounts.biz.common.uploadFileWithFileInfo';
            _index++;
            //如果存在url,则直接跳出循环
            if (hasFile) {
                return false;
            }
            request(o).then(res => {
                if (res.code == 0) {
                    this._num++;
                    current--;
                    var _obj = res.data;
                    document.querySelector("div#upload_progress_box .progress_box_inner").style.width = this._num / len * 100 + '%';
                    if (this._num == len) {
                        document.querySelector("div#upload_progress_box").style.display = "none";
                    }
                    //如果存在url,则直接跳出循环
                    if (res.data.fileUrl) {
                        document.querySelector("div#upload_progress_box").style.display = "none";
                        hasFile = true;
                        _allCallback(res.data.fileUrl);
                        return false;
                    }
                }
            }).catch(res => {
                current--;
            });
        }

        return false; */

  for (let i = len - 1; i >= 0; i--) {
    var _index = i
    var fileBase64 = transformArrayBufferToBase64(arr[i])
    var oParams = getParams(_index, fileBase64)
    var o = {}
    oParams.file = oParams.fileType + '@' + fileBase64

    o.method = 'POST'
    o.data = oParams
    o.url = (that.options.url || that.config.url) + '?method=glsx.accounts.biz.common.uploadFileWithFileInfo'
    //fileFragmentUpload(o);
    //如果存在url,则直接跳出循环
    if (hasFile) {
      return false
    }
    request(o).then(res => {
      if (res.code == 0) {
        _num++
        var _obj = res.data

        // 如果有进度条,则设置对应的进度条属性
        // if (that.options.showprocess) {
        //   document.querySelector('#' + that.config.id + ' div#upload_progress_box .progress_box_inner').style.width = (_num / len) * 100 + '%'
        //   if (_num == len) {
        //     document.querySelector('#' + that.config.id + ' div#upload_progress_box').style.display = 'none'
        //   }
        // }

        //如果存在url,则直接跳出循环
        if (res.data.fileUrl) {
          if (that.options.showprocess) {
            // document.querySelector('#' + that.config.id + ' div#upload_progress_box').style.display = 'none'
          }
          hasFile = true
          _allCallback(res.data.fileUrl)
          return false
        }
      }
    })
  }
}

/**
 * 所有分片上传成功回调函数
 */
function _allCallback(url) {
  //console.log(url);
  if (url) {
    that.options.success ? that.options.success(url) : ''
  }
}

/**
 * 分片上传
 */
function fileFragmentUpload(oParams) {
  request()
    .then(res => {
      if (res.code == 0) {
        this._num++
        var _obj = res.data
        // 如果有进度条,则设置对应的进度条属性
        // if (that.options.showprocess) {
        //   document.querySelector('#' + that.config.id + ' div#upload_progress_box .progress_box_inner').style.width = (this._num / this.len) * 100 + '%'
        //   if (this._num == this.len) {
        //     document.querySelector('#' + that.config.id + ' div#upload_progress_box').style.display = 'none'
        //   }
        // }

        _allCallback(res.data.fileUrl)
        /* if(_obj.fileUrl){
                   that.options.success? (that.options.success)(_obj.fileUrl):''
                }; */
      }
    })
    .catch(res => {
      fileFragmentUpload(oParams)
    })
}

/**
 * 生成签名
 */
function createSign(params) {
  var secret = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'
  var noSignAttr = []
  delete params.sign
  noSignAttr.push('refreshTable')
  var keys = Object.keys(params).sort()
  var str = []
  var obj = null
  for (const key in params) {
    obj = params[key]
    if (obj === null || obj === undefined) {
      obj = ''
    } else if (typeof obj === 'object') {
      obj = JSON.stringify(obj)
    }
    params[key] = obj
  }
  keys.forEach(e => {
    !noSignAttr.includes(e) && str.push(e + params[e])
  })
  params.sign = MD5(secret + str.join('') + secret)
  return params
}

/**
 * 获取参数
 */
function getParams(index, oInfo) {
  var o = that.options
  var k = that.config
  var oParams = {}
  var len = w.list.length
  var size = Number(o.size * 1024 * 1024)
  // console.log(o.size)
  // console.log(w);
  // console.log('个数:' + w.list.length);
  // console.log('当前个数' + index)
  if (len > 1 && index == len - 1) {
    size = w.fileSize - o.size * 1024 * 1024 * (w.list.length - 2)
  }

  //只有一个分片
  if (w.list.length == 1) {
    size = w.fileSize
  }

  // var spark = new MD5()
  // spark.append(oInfo)

  oParams.app_key = k.app_key
  oParams.v = k.v
  oParams.timestamp = new Date().getTime()
  oParams.format = k.format
  oParams.source = '2323242323'
  oParams.method = 'glsx.accounts.biz.common.uploadFileWithFileInfo'

  oParams.token = w.token
  oParams.number = index + 1
  oParams.fileType = w.fileType
  oParams.fileName = w.fileName
  oParams.fileSize = w.fileSize
  oParams.fileFragmentSize = size
  oParams.fileUpSum = w.list.length
  oParams.fileMD5 = w.fileMD5
  oParams.fragmentMD5 = MD5(oInfo)

  // for (let k in m) {
  //     oParams.append(k, m[k]);
  // }
  return createSign(oParams)
}

/**
 * 获取token
 */
function getToken(file) {
  return new Promise(function(resolve, reject) {
    var _obj = that.config
    var o = {}
    var oParams = {}
    oParams.fileSize = file.size
    oParams.fileUpSum = Math.ceil(file.size / (that.options.size * 1024 * 1024))
    oParams.fileType = getFileType(file.name)
    oParams.fileName = file.name
    oParams.method = 'glsx.accounts.biz.common.getUploadFileToken'

    oParams.app_key = _obj.app_key
    oParams.v = _obj.v
    oParams.format = _obj.format

    //这三个参数动态,由用户自己上传
    oParams.lastOperatorId = '11111'
    oParams.lastOperatorName = 'jack'
    oParams.source = '2323242323'

    oParams.timestamp = new Date().getTime()

    //把文件信息存起来
    w.fileSize = oParams.fileSize //文件大小
    w.fileUpSum = oParams.fileUpSum //分片个数
    w.fileType = oParams.fileType //文件类型
    w.fileName = oParams.fileName //文件名称

    o.url = that.options.url || that.config.url || _obj.url
    o.data = createSign(oParams)
    o.method = 'GET'
    request(o)
      .then(res => {
        if (res.code == 0) {
          var _data = res.data || {}
          w.token = _data.token
          resolve(_data.token)
        }
      })
      .catch(res => {
        reject(res)
      })
  })
}

/**
 * 参数序列化
 */
function formRequestData(data) {
  var _sendstr = null
  if (data) {
    _sendstr = ''
    for (var i in data) {
      _sendstr += (_sendstr ? '&' : '') + i + '=' + encodeURIComponent(data[i])
    }
  }
  return _sendstr
}

/**
 * 检查文件是否上传
 */
function checkFileIsUpload(md5) {
  return new Promise((resolve, reject) => {
    if (!md5) {
      return false
    }
    var _obj = that.config
    var o = {}
    var oParams = {}
    oParams.fileMD5 = md5
    oParams.token = _obj.token
    oParams.app_key = _obj.app_key
    oParams.v = _obj.v
    oParams.format = _obj.format
    oParams.timestamp = new Date().getTime()
    oParams.method = 'glsx.accounts.biz.common.checkAndListFragmentDetail'

    o.url = that.options.url || that.config.url || _obj.url
    o.data = createSign(oParams)
    o.method = 'GET'
    request(o)
      .then(res => {
        if (res.code == 0) {
          resolve(res)
        }
      })
      .catch(res => {
        reject(res)
      })
  })
}

/**
 * 文件切片
 */
function fileSlice(oParams) {
  if (!oParams) {
    return false
  }
  var o = that.options
  var file = oParams.file
  var cellBlod = []
  var cell = Number(o.size) * 1024 * 1024 //单个分片的大小
  var size = oParams.size //文件大小
  var num = Math.ceil(size / cell) //计算分片的个数
  if (num == 1) {
    cellBlod.push(file)
  } else {
    for (var i = 0; i < num; i++) {
      var s = i * cell
      var e = (i + 1) * cell
      var m = ''
      if (file.slice) {
        m = file.slice(s, e)
      }

      //兼容firefox
      if (file.mozSlice) {
        m = file.mozSlice(s, e)
      }

      // 兼容webkit
      if (file.webkitSlice) {
        m = file.webkitSlice(s, e)
      }
      cellBlod.push(m)
    }
  }

  return cellBlod
}

/**
 * 获取文件类型
 */
function getFileType(file) {
  if (!file) {
    return false
  }
  var arr = file.split('.')
  return arr[arr.length - 1]
}

/**
 * arrbuffer转换成base64
 */
function transformArrayBufferToBase64(buffer) {
  var binary = ''
  var bytes = new Uint8Array(buffer)
  for (var len = bytes.byteLength, i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i])
  }
  return window.btoa(binary)
}

//暴露对象
export default upload