All files / src/utils upload.js

0% Statements 0/44
0% Branches 0/31
0% Functions 0/7
0% Lines 0/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                       
/**
 * @author SoldierAb
 * @description 文件上传
 * @param {any} option
 * @since 18-12-29
 * @example
 *
 * upload({
 *   headers:headers,                                           //响应头
 *   withCredentials: withCredentials,                          //是否包含cookie
 *   file: file,                                                //文件
 *   data: data,                                                //数据
 *   filename: name,                                            //文件名
 *   action: action,                                            //接口
 *   onProgress: e => {                                         //当前进度回调
 *       this.handleProgress(e, file);
 *   },
 *   onSuccess: res => {                                        //上传成功回调
 *       this.handleSuccess(res, file);
 *   },
 *   onError: (err, response) => {                              //上传出错回调
 *       this.handleError(err, response, file);
 *   }
 * });
 *
 * @returns
 *
 */
 
 
 
const upload = (option,type="post") => {
    if (typeof XMLHttpRequest === 'undefined') {
      return;
    }
 
    const xhr = new XMLHttpRequest();
    const action = option.action;      //请求url
 
    if (xhr.upload) {
      xhr.upload.onprogress = function progress(e) {
        if (e.total > 0) {
          e.percent = e.loaded / e.total * 100;
        }
        option.onProgress(e);
      };
    }
    //文件formData
    const formData = new FormData();
    if (option.data) {
      Object.keys(option.data).map(key => {
        formData.append(key, option.data[key]);
      });
    }
    if(option.filename&&option.file) formData.append(option.filename, option.file);
 
 
    xhr.onerror = function error(e) {
      option.onError(e);
    };
 
    xhr.onload = function onload() {
      if (xhr.status < 200 || xhr.status >= 300) {
        return option.onError(getError(action, option, xhr,type), getBody(xhr));
      }
 
      option.onSuccess(getBody(xhr));
    };
 
    xhr.open(type, action, true);
 
    //是否cookie
    if (option.withCredentials && 'withCredentials' in xhr) {
      xhr.withCredentials = true;
    }
 
    const headers = option.headers || {};
 
    // if (headers['X-Requested-With'] !== null) {
    //   xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    // }
 
    for (let item in headers) {
      if (headers.hasOwnProperty(item) && headers[item] !== null) {
        xhr.setRequestHeader(item, headers[item]);
      }
    }
 
    xhr.send(formData);
 
  }
 
 
 
  /**
   *
   * @description 错误获取
   * @param {any} action
   * @param {any} option
   * @param {any} xhr
   * @returns
   */
  const getError = (action, option, xhr,type) => {
    const msg = `fail to ${type} ${action} ${xhr.status}`;
    const err = new Error(msg);
    err.status = xhr.status;
    err.method = type;
    err.url = action;
    return err;
  }
 
  /**
   *
   * @description 返回内容获取
   * @param {any} xhr
   * @returns
   */
  const getBody = (xhr) => {
    const text = xhr.responseText || xhr.response;
    if (!text) {
      return text;
    }
    try {
      return JSON.parse(text);
    } catch (e) {
      return text;
    }
  }
 
 
  export default upload;