如何在XMLHttpRequest中获取实际文件?

时间:2016-05-14 09:55:24

标签: javascript php ajax file-upload xmlhttprequest

如何在XMLHttpRequest中获取实际文件? 使用evt.target.files返回一个fileList对象,我无法获取php端的实际文件,以便保存在服务器上。

下面是代码,我附上了一张图片,显示了从php代码print_r($_POST);

返回的responseText

function handleFileSelect(evt) {

  reader = new FileReader();
  reader.onload = function(e) {
    // Ensure that the progress bar displays 100% at the end.
    progress.style.width = '100%';
    progress.textContent = '100%';
    setTimeout("document.getElementById('progress_bar').className='';", 2000);


    ///////////THE JSON/////////////to encase file in JSON object
    var sendFile = function(url, successHandler, errorHandler) {
      var xhr = typeof XMLHttpRequest != 'undefined' ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
      xhr.open('post', url, true);

      //XHR progress tracking
      xhr.upload.onprogress = function(event) {
        //var native_progress = document.getElementById("native_progress");
        //alert('in native_progress function');
        if (event.lengthComputable) {
          var complete = (event.loaded / event.total * 100 | 0);
          native_progress.value = native_progress.innerHTML = complete;
        }
      };

      xhr.onreadystatechange = function() {
        var status;
        var data;
        // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
        if (xhr.readyState == 4) { // `DONE`
          status = xhr.status;
          if (status == 200) {
            //data = JSON.parse(xhr.responseText);
            data = xhr.responseText;
            successHandler && successHandler(data);
          } else {
            errorHandler && errorHandler(status);
          }
        }
      };

      var formData = new FormData();
      formData.append('file', evt.target.files[0]);
      //xhr.setRequestHeader("Content-type", "multipart/gorm-data");
      //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhr.send(formData);
    };

    sendFile('/ePub_Reader/temp_upload/save.php', function(data) {
      alert('Response Text: ' + data);
    }, function(status) {
      alert('Something went wrong.');
    });
    ///////////THE JSON - end/////////////

    // Read in the image file as a binary string.
    //reader.readAsBinaryString(evt.target.files[0]);
    reader.readAsDataURL(evt.target.files[0]);
  }

}

document.getElementById('files').addEventListener('change', handleFileSelect, false);

Alert Showing php responseText generated by <code>print_r($_POST);</code>

1 个答案:

答案 0 :(得分:0)

将单个文件追加到FormData对象而不是FileList

formData.append('file', evt.target.files[0]);