使用XHR请求发送文件

时间:2011-08-02 13:27:43

标签: javascript xmlhttprequest

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)); 
}

您好,我已经从网站上复制了此代码,而我正在尝试了解它的工作原理。我想知道将文件发送到php的两种方法有什么区别。使用一个而不是另一个有什么好处吗?

1 个答案:

答案 0 :(得分:1)

HTML5 spec中描述了btoa功能。似乎并非所有浏览器都实现了此方法。

以下是您的示例中的source article

第一个示例(sendAsBinary)创建RFC 2388中定义的表单发布数据。

第二个示例(btoa)使用自定义有效负载(文件内容的base64编码值)。

相关问题