在使用ant design
开发后台业务过程当中,遇到了给upload
组件配置后台服务器的问题。由于用习惯了七牛云的快速易用,以及喜欢它的自动压缩接口,所以第一反应就是想怎么配置上传到七牛云上面。
不过通过多番搜寻,并没找到好的解决方案。官方推荐参考的jQuery-File-Upload服务端上传接口实现测试了几个nodejs
的实现,发现好久没有维护了,存在一些问题。因而只能从阅读ant design
源代码来看能不能怎么修改upload
的上传方式,从而实现提交图片过去。javascript
首先从ant design的upload组件源码能够看到,它是基于这个upload组件编写的。再看该upload组件,获得具体的request实现:html
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上传的实现:java
/* * 本示例演示七牛云存储表单上传 * * 按照如下的步骤运行示例: * * 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:node
formData.append('token', token);
而经过upload的request源码又能够知道,能够经过option.data传过来的参数执行formData.append('token', token);
,该部分的源码以下:react
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
组件上传图片到七牛云:jquery
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>
最后划重点:git
BTW, 若是使用的是七牛云其余地区如华南地区的Bucket,须要替换使用其余地区的上传域名进action,具体可参考这里。Enjoy it!
github