tool

原生js上传组件xhr

2020-01-14  本文已影响0人  吞风咽雪
既分高低 也决生死
  1. [库]
//图片上传类
class AjaxUploader {
  constructor(config) {
    var me = this,
      isUploading = false,
      formData = new FormData(),
      fileInput = document.createElement('input');
    fileInput.type = 'file';
    if (config.accept) {
      fileInput.accept = config.accept;
    } else {
      fileInput.accept = 'http://localhost/eg_img2.jpg';
    }
    //fileInput.style.position='absolute';
    fileInput.style.left = '0';
    fileInput.style.top = '0';
    fileInput.style.width = '100%';
    //fileInput.style.height='100%';
    //fileInput.style.opacity='0';

    this.dom = config.dom;
    this.url = config.url || O_CONST.uploadServer;
    this.uploadsuccess = config.uploadsuccess;
    this.uploaderror = config.uploaderror;
    this.onchange = config.onchange;

    fileInput.addEventListener("change", function () {
      if (this.files.length < 1) {
        return
      }
      me.onchange(fileInput.files[0]);
    }, false);

    // this.getImageInfo = getImageInfo;
    // this.getVideoInfo = getVideoInfo;
    this.addPostData = function (k, v) {
      formData.append(k, v)
    };
    this.upload = function () {
      if (isUploading) {
        return
      }
      var xhr = new XMLHttpRequest();
      formData.append('file', fileInput.files[0]);
      formData.append('type', 'photo');
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
          isUploading = false;
          if (xhr.status == 200) {
            me.uploadsuccess(xhr.response)
          } else {
            me.uploaderror()
          }
        }
      };
      xhr.open('POST', this.url);
      xhr.send(formData);
      isUploading = true;
    };
    this.reset = function () {
      isUploading = false;
      fileInput.value = "";
      formData = new FormData();
    };
    this.dom.appendChild(fileInput);
  }
  getVideoInfo(file, cb) {
    var v = document.createElement('video'),
      obj = {
        name: file.name,
        size: file.size,
        type: file.type
      };
    v.style.cssText = 'position:fixed;top:0;z-index:99;width:100px;opacity:0;';
    v.addEventListener("loadedmetadata", function () {
      obj.width = v.videoWidth;
      obj.height = v.videoHeight;
      obj.duration = v.duration;
    });
    v.addEventListener("canplay", function () {
      window.URL.revokeObjectURL(v.src);
      v.src = '';
      v.parentNode.removeChild(v);
      v = null;
      cb(obj);
    });
    document.body.appendChild(v);
    v.src = window.URL.createObjectURL(file);
  }
  getImageInfo(imgFile, cb) {
    var obj = {
      name: imgFile.name,
      size: imgFile.size,
      type: imgFile.type
    };
    if (!(imgFile instanceof File)) {
      console.error('不是文件对象');
      return;
    }
    var img = new Image();
    img.onload = function () {
      obj.width = img.naturalWidth;
      obj.height = img.naturalHeight;
      window.URL.revokeObjectURL(img.src);
      cb(obj);
    };
    img.src = window.URL.createObjectURL(imgFile);
  }
}
  1. [调用]
//初始化上传组件
  initUpload(result) {
    result.fileUploader = new AjaxUploader({
      dom: result.domSet.find('.rt-uploadBtn')[0],
      onchange: function (file) {
        result.fileUploader.getImageInfo(file, function (d) {
          if (d.width != 888 || d.height < 380 || d.height > 600) {
            alert('上传失败!图片不符合限制');
            result.fileUploader.reset()
            return;
          }
         //TODO 更新视图 
          result.fileUploader.upload();
        });
      },
      uploadsuccess: function (d) {
        d = JSON.parse(d);
        console.log('上传返回', d);
        var imgUrl = d.data.url
        result.fileUploader.reset()
        //TODO 更新视图 
      },
      uploaderror: function () {
        alert('图片上传失败');
        result.fileUploader.reset();
      }
    })
  }
上一篇下一篇

猜你喜欢

热点阅读