XMLHttpRequest()格式错误的帖子标题HTML5上传

时间:2014-07-04 17:08:50

标签: php ajax perl xmlhttprequest

我使用以下代码将文件从手机上传到网络服务器。如果我删除了ajax调用并使用表单只有上传工作。如果我使用ajax PHP或CGI scipts我用来处理上传失败。 CGI给我一个格式错误的帖子标题错误。

  <script type="text/javascript">
  function uploadFile() {

    var fd = new FormData();

          var count = document.getElementById('fileUpload').files.length;


          for (var index = 0; index < count; index ++)

          {

                 var file = document.getElementById('fileUpload').files[index];
                 alert(file.name);

          } 

    var xhr = new XMLHttpRequest();

    xhr.upload.addEventListener("progress", uploadProgress, false);

    xhr.addEventListener("load", uploadComplete, false);

    xhr.addEventListener("error", uploadFailed, false);

    xhr.addEventListener("abort", uploadCanceled, false);

    xhr.open("POST", "upload.pl");

    xhr.send(fd);

  }

  function uploadProgress(evt) {

    if (evt.lengthComputable) {

      var percentComplete = Math.round(evt.loaded * 100 / evt.total);

      document.getElementById('progress').innerHTML = percentComplete.toString() + '%';

    }

    else {

      document.getElementById('progress').innerHTML = 'unable to compute';

    }

  }

  function uploadComplete(evt) {


    alert(evt.target.responseText);

  }

  function uploadFailed(evt) {

    alert("There was an error attempting to upload the file.");

  }

  function uploadCanceled(evt) {

    alert("The upload has been canceled by the user or the browser dropped the connection.");

  }

</script>


    <form id="form1" enctype="multipart/form-data" method="post" action="upload.pl">
    <div>
      <label for="fileUpload">Take or Select Images</label><br />
      <input type="file" name="fileUpload" id="fileUpload" accept="image/*" capture="camera" /><br />
      <input type="text" name="email" value="" />
    </div>
    <div id="details"></div>
    <div>
      <input type="button" onclick="uploadFile();" value="Upload" />
    </div>
    <div id="progress"></div>
    </form>

1 个答案:

答案 0 :(得分:1)

您从未使用任何数据填充fd!从我在Using FormData Objects中读到的内容

var fd = new FormData();

应该是

var fd = new FormData(document.getElementById('form1'));