Page 245 - Web性能权威指南
P. 245

formData.append('id', 123456);
                   formData.append('topic', 'performance');
                   var xhr = new XMLHttpRequest();
                   xhr.open('POST', '/upload');
                   xhr.onload = function() { ... };
                   xhr.send(formData); ➌

                   var xhr = new XMLHttpRequest();
                   xhr.open('POST', '/upload');
                   xhr.onload = function() { ... };
                   var uInt8Array = new Uint8Array([1, 2, 3]); ➍
                   xhr.send(uInt8Array.buffer); ➎

               ➊ 把简单的文本字符串上传到服务器
               ➋ 通过 FormData API 动态创建表单数据
               ➌ 向服务器上传 multipart/form-data 对象
               ➍ 创建无符号、8 字节整型的有类型数组(ArrayBuffer)
               ➎ 向服务器上传字节块

               XHR 对 象 的 send() 方 法 可 以 接 受 DOMString、Document、FormData、Blob、File 及
               ArrayBuffer 对象,并自动完成相应的编码,设置适当的 HTTP 内容类型 (content-type),
               然后再分派请求。需要发送二进制 Blob 或上传用户提交的文件?简单,取得对该对
               象的引用,传给 XHR。事实上,多写几行代码,还可以把大文件切成几小块:

                   var blob = ...; ➊
                   const BYTES_PER_CHUNK = 1024 * 1024; ➋
                   const SIZE = blob.size;

                   var start = 0;
                   var end = BYTES_PER_CHUNK;
                   while(start < SIZE) { ➌
                     var xhr = new XMLHttpRequest();
                     xhr.open('POST', '/upload');
                     xhr.onload = function() { ... };

                     xhr.setRequestHeader('Content-Range', start+'-'+end+'/'+SIZE); ➍
                     xhr.send(blob.slice(start, end)); ➎


                     start = end;
                     end = start + BYTES_PER_CHUNK;
                   }
               ➊ 任意数据(二进制或文本)的二进制对象
               ➋ 将块大小设置为 1 MB



               232   |   第 15 章
   240   241   242   243   244   245   246   247   248   249   250