我知道有很多类似的问题,但是我仍然没有找到解决问题的方法。我正在尝试使用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; };
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 . ' }'; ?>;
但是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; };
它可以正常工作,但文件大小只有8mb左右。当我尝试发送大小超过8mb的文件时,该var $_FILES['file']再次变空
$_FILES['file']
注意:“ file” var对应于诸如document.getElementsById(’fileInput’)。files [0]之类的内容;
为了避免post_max_size限制问题…同时也避免了内存不足的问题:
xhr.open("put", "upload.php", true);
xhr.setRequestHeader("X-File-Name", file.name); xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.send(file);
请注意,可以通过input [type = file] DOM对象的“ files”属性直接获取File对象
$filename = $_SERVER['HTTP_X_FILE_NAME']; $filesize = $_SERVER['HTTP_X_FILE_SIZE'];
$filename = $_SERVER['HTTP_X_FILE_NAME'];
$filesize = $_SERVER['HTTP_X_FILE_SIZE'];
$in = fopen('php://input','r');
这样您就可以无限制地发送非常大的文件(1GB或更大)!!!
此代码适用于FireFox 4 +,Chrome 6 +,IE10 +