简体   繁体   English

使用XHR请求发送文件

[英]sending files using XHR request

if(up.xhr.sendAsBinary != null) { //firefox

    up.xhr.open('POST', '/html5_upload.php?up=true', true);

    var boundary = 'xxxxxxxxx';

    var body = '--' + boundary + "\r\n";  
    body += "Content-Disposition: form-data; name='upload'; filename='" + up.processing.name + "'\r\n";  
    body += "Content-Type: application/octet-stream\r\n\r\n";  
    body += binary + "\r\n";  
    body += '--' + boundary + '--';  

    up.xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
    up.xhr.sendAsBinary(body);          

} else { //for browsers that don't support sendAsBinary yet

    up.xhr.open('POST', '/html5_upload.php?up=true&base64=true', true);

    up.xhr.setRequestHeader('UP-FILENAME', up.processing.name);
    up.xhr.setRequestHeader('UP-SIZE', up.processing.size);
    up.xhr.setRequestHeader('UP-TYPE', up.processing.type);

    up.xhr.send(window.btoa(binary)); 
}

Hi I've copied this code from a website and I'm trying to understand hows it works. 嗨,我已经从网站复制了此代码,并且试图了解它的工作原理。 I'm wondering what's the difference between two methods of sending the file over to php. 我想知道将文件发送到php的两种方法之间的区别是什么。 Is there any benfits in using one instead of the other? 使用一个而不是另一个有什么好处吗?

The btoa function is described in the HTML5 spec . HTML5规范中描述了btoa函数。 It appears not all browser have this method implemented. 似乎并非所有浏览器都实现了此方法。

Here is the source article for your example. 这是您的示例的源文章

The 1st example (sendAsBinary) creates the form post data as defined in RFC 2388 . 第一个示例(sendAsBinary)创建RFC 2388中定义的表单发布数据。

The 2nd example (btoa) uses a custom payload (base64 encoded value of file contents). 第二个示例(btoa)使用自定义有效负载(文件内容的base64编码值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM