Dan*_*nte 5 javascript ajax upload file xmlhttprequest
我知道有很多类似的问题,但我仍然没有找到解决问题的方法.我正在尝试使用XMLHttpRequest上传文件,因此我开发了以下代码:
var sendFiles = function(url,onload,onerror,file,headers){
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp'),
upload = xhr.upload;
API.addEvent(xhr,'readystatechange',function(){
if(xhr.readyState==4)
if((xhr.status>=200 && xhr.status<300) || xhr.status==304){
this.response = this.response || this.responseText;
onload.call(xhr);
}else onerror.call(xhr);
});
xhr.open('POST',url,true);
for(var n=0;n<headers.length;n++)
xhr.setRequestHeader(headers[n]);
xhr.send(file);
return xhr;
};
Run Code Online (Sandbox Code Playgroud)
PHP端脚本是:
<?php
header('Content-type: text/html;charset=ISO-8859-1');
$status = 0;
if(@copy($_FILES['file']['tmp_name'],'test\\' . $_FILES['file']['name']))
$status = 1;
else
$err = '0';
echo '{
"status": ' . $status . '
}';
?>;
Run Code Online (Sandbox Code Playgroud)
但是var $ _FILES ['file']似乎是空的,这意味着文件没有被发送到服务器.然后我决定在下面的代码中使用FormData对象
var sendFiles = function(url,onload,onerror,file,headers){
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp'),
upload = xhr.upload,
formData = new FormData();
formData.append('file',file);
API.addEvent(xhr,'readystatechange',function(){
if(xhr.readyState==4)
if((xhr.status>=200 && xhr.status<300) || xhr.status==304){
this.response = this.response || this.responseText;
onload.call(xhr);
}else onerror.call(xhr);
});
xhr.open('POST',url,true);
for(var n=0;n<headers.length;n++)
xhr.setRequestHeader(headers[n]);
xhr.send(formData);
return xhr;
};
Run Code Online (Sandbox Code Playgroud)
它有效,但只有文件大小低至约8mb.当我尝试发送大小超过8mb的文件时,var $_FILES['file']再次变为空
注意:'file'var对应于document.getElementsById('fileInput').files [0];
Opt*_*pty 17
为了避免post_max_size限制问题......但双方都存在内存不足的问题:
使用PUT而不是POST:
xhr.open("put", "upload.php", true);
添加自定义标头以指定原始FileName和FileSize:
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
直接在XHR发送方法中使用File对象:
xhr.send(file);
请注意,可以通过输入[type = file] DOM对象的"files"属性直接获取File对象
通过$ _SERVER读取自定义标头:
$filename = $_SERVER['HTTP_X_FILE_NAME'];
$filesize = $_SERVER['HTTP_X_FILE_SIZE'];
使用php:// input读取文件数据:
$in = fopen('php://input','r');
然后你就可以发送非常大的文件(1GB或更多),没有任何限制!
此代码适用于FireFox 4 +,Chrome 6 +,IE10 +
| 归档时间: |
|
| 查看次数: |
23212 次 |
| 最近记录: |