Ant Design upload 组件疾速设置运用七牛云

在运用ant design开辟背景营业过程当中,遇到了给upload组件设置背景服务器的题目。由于用习惯了七牛云的疾速易用,以及喜好它的自动紧缩接口,因而第一回响反映就是想怎样设置上传到七牛云上面。
不过经过量番征采,并没找到好的解决方案。官方引荐参考的jQuery-File-Upload服务端上传接口完成测试了几个nodejs的完成,发明良久没有保护了,存在一些题目。因而只能从浏览ant design源代码来看能不能怎样修正upload的上传体式格局,从而完成提交图片过去。

首先从ant design的upload组件源码能够看到,它是基于这个upload组件编写的。再看该upload组件,获得详细的request完成:

function getError(option, xhr) {
  const msg = `cannot post ${option.action} ${xhr.status}'`;
  const err = new Error(msg);
  err.status = xhr.status;
  err.method = 'post';
  err.url = option.action;
  return err;
}

function getBody(xhr) {
  const text = xhr.responseText || xhr.response;
  if (!text) {
    return text;
  }

  try {
    return JSON.parse(text);
  } catch (e) {
    return text;
  }
}

// option {
//  onProgress: (event: { percent: number }): void,
//  onError: (event: Error, body?: Object): void,
//  onSuccess: (body: Object): void,
//  data: Object,
//  filename: String,
//  file: File,
//  withCredentials: Boolean,
//  action: String,
//  headers: Object,
// }
export default function upload(option) {
  const xhr = new XMLHttpRequest();

  if (option.onProgress && xhr.upload) {
    xhr.upload.onprogress = function progress(e) {
      if (e.total > 0) {
        e.percent = e.loaded / e.total * 100;
      }
      option.onProgress(e);
    };
  }

  const formData = new FormData();

  if (option.data) {
    Object.keys(option.data).map(key => {
      formData.append(key, option.data[key]);
    });
  }

  formData.append(option.filename, option.file);

  xhr.onerror = function error(e) {
    option.onError(e);
  };

  xhr.onload = function onload() {
    // allow success when 2xx status
    // see https://github.com/react-component/upload/issues/34
    if (xhr.status < 200 || xhr.status >= 300) {
      return option.onError(getError(option, xhr), getBody(xhr));
    }

    option.onSuccess(getBody(xhr), xhr);
  };


  xhr.open('post', option.action, true);

  // Has to be after `.open()`. See https://github.com/enyo/dropzone/issues/179
  if (option.withCredentials && 'withCredentials' in xhr) {
    xhr.withCredentials = true;
  }

  const headers = option.headers || {};

  // when set headers['X-Requested-With'] = null , can close default XHR header
  // see https://github.com/react-component/upload/issues/33
  if (headers['X-Requested-With'] !== null) {
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  }

  for (const h in headers) {
    if (headers.hasOwnProperty(h) && headers[h] !== null) {
      xhr.setRequestHeader(h, headers[h]);
    }
  }
  xhr.send(formData);

  return {
    abort() {
      xhr.abort();
    },
  };
}

至此上传的逻辑一览无余,那末能够怎样革新呢?再翻阅一下七牛云的文档,获得一个应用js上传的完成:

/*
 *   本示例演示七牛云存储表单上传
 *
 *   根据以下的步骤运转示例:
 *
 *   1. 填写token。须要您不晓得怎样天生token,能够点击右边的链接天生,然后将结果复制粘贴过来。
 *   2. 填写key。假如您在天生token的过程当中指定了key,则将其输入至此。不然留空。
 *   3. 姓名是一个自定义的变量,假如天生token的过程当中指定了returnUrl和returnBody,
 *      而且returnBody中指定了希冀返回此字段,则七牛会将其返回给returnUrl对应的营业服务器。
 *      callbackBody亦然。
 *   4. 挑选恣意一张照片,然后点击提交即可
 *
 *   现实开辟中,您能够经由过程后端开辟言语动态天生这个表单,将token的hidden属性设置为true并对其举行赋值。
 *
 *  **********************************************************************************
 *  * 孝敬代码:
 *  * 1. git clone git@github.com:icattlecoder/jsfiddle
 *  * 2. push代码到您的github库
 *  * 3. 测试结果,接见 http://jsfiddle.net/gh/get/jquery/1.9.1/<Your GitHub Name>/jsfiddle/tree/master/ajaxupload
 *  * 4. 提pr
 *   **********************************************************************************
 */
$(document).ready(function() {
    var Qiniu_UploadUrl = "http://up.qiniu.com";
    var progressbar = $("#progressbar"),
        progressLabel = $(".progress-label");
    progressbar.progressbar({
        value: false,
        change: function() {
            progressLabel.text(progressbar.progressbar("value") + "%");
        },
        complete: function() {
            progressLabel.text("Complete!");
        }
    });
    $("#btn_upload").click(function() {
        //一般上传
        var Qiniu_upload = function(f, token, key) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', Qiniu_UploadUrl, true);
            var formData, startDate;
            formData = new FormData();
            if (key !== null && key !== undefined) formData.append('key', key);
            formData.append('token', token);
            formData.append('file', f);
            var taking;
            xhr.upload.addEventListener("progress", function(evt) {
                if (evt.lengthComputable) {
                    var nowDate = new Date().getTime();
                    taking = nowDate - startDate;
                    var x = (evt.loaded) / 1024;
                    var y = taking / 1000;
                    var uploadSpeed = (x / y);
                    var formatSpeed;
                    if (uploadSpeed > 1024) {
                        formatSpeed = (uploadSpeed / 1024).toFixed(2) + "Mb\/s";
                    } else {
                        formatSpeed = uploadSpeed.toFixed(2) + "Kb\/s";
                    }
                    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                    progressbar.progressbar("value", percentComplete);
                    // console && console.log(percentComplete, ",", formatSpeed);
                }
            }, false);

            xhr.onreadystatechange = function(response) {
                if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText != "") {
                    var blkRet = JSON.parse(xhr.responseText);
                    console && console.log(blkRet);
                    $("#dialog").html(xhr.responseText).dialog();
                } else if (xhr.status != 200 && xhr.responseText) {

                }
            };
            startDate = new Date().getTime();
            $("#progressbar").show();
            xhr.send(formData);
        };
        var token = $("#token").val();
        if ($("#file")[0].files.length > 0 && token != "") {
            Qiniu_upload($("#file")[0].files[0], token, $("#key").val());
        } else {
            console && console.log("form input error");
        }
    })
})

经由过程审视个中的中心逻辑能够晓得,*它的上传逻辑与antd 的upload组件的中心区分就是formData增加了七牛云上传token:

formData.append('token', token);

而经由过程upload的request源码又能够晓得,能够经由过程option.data传过来的参数实行formData.append('token', token);,该部份的源码以下:

const formData = new FormData();

  if (option.data) {
    Object.keys(option.data).map(key => {
      formData.append(key, option.data[key]);
    });
  }

由此,再参阅ant design官方文档能够晓得,运用Upload组件时,能够经由过程data API传入自定义的data,那末自此就能够获得一个简约的方法,经由过程以下sample code就能够完成Upload组件上传图片到七牛云:

const QINIU_SERVER = 'http://up.qiniu.com'
data = {
    token: 'PUT-YOUR-TOKEN-HERE',
  }
<Upload
    action={QINIU_SERVER}
    listType="picture-card"
    className="upload-list-inline"
    onChange={this.onChange}
    onPreview={this.handlePreview}
    fileList={fileList}
    data={this.data}
    >
        {uploadButton}
</Upload>

末了划重点:

BTW, 假如运用的是七牛云其他地区如华南地区的Bucket,须要替代运用其他地区的上传域名进action,详细可参考这里
Enjoy it!

    原文作者:Anderson_liu
    原文地址: https://segmentfault.com/a/1190000011174923
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞