从xmlhttprequest清空responseText

时间:2011-07-02 17:41:16

标签: javascript xmlhttprequest

我使用ajax上传文件,为什么xmlhttprequest.responseText中的responseText返回为空?

我的代码:

req = new XMLHttpRequest(); 
req.file = file; 
req.addEventListener('change', changeProgress); 
 req.onreadystatechange = 
function() {
if(this.readyState == 4) {
  //etc.. 
alert(req.responseText);
}
}; 
req.open('POST','/upload',true);
req.send(file);

1 个答案:

答案 0 :(得分:2)

出于安全原因,不支持在XMLHttpRequest对象中上传文件

编辑:但是,这可以使用XMLHttpRequest 2

function upload(blobOrFile) {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/server', true);
  xhr.onload = function(e) { ... };

  // Listen to the upload progress.
  var progressBar = document.querySelector('progress');
  xhr.upload.onprogress = function(e) {
    if (e.lengthComputable) {
      progressBar.value = (e.loaded / e.total) * 100;
      progressBar.textContent = progressBar.value; // Fallback for unsupported browsers.
    }
  };

  xhr.send(blobOrFile);
}

upload(new Blob(['hello world'], {type: 'text/plain'}));