ajax HTML5上传图片

前端之家收集整理的这篇文章主要介绍了ajax HTML5上传图片前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参考:
http://robertnyman.com/2013/02/11/using-formdata-to-send-forms-with-xhr-as-keyvalue-pairs/
https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

HTML:
<form enctype="multipart/form-data" method="post" name="fileinfo">
  <label>Your email address:</label>
  <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
  <label>Custom file label:</label>
  <input type="text" name="filelabel" size="12" maxlength="32" /><br />
  <label>File to stash:</label>
  <input type="file" name="file" required />
  <input type="submit" value="Stash the file!" />
</form>
<div id="output"></div>





Javascript:
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit',function(ev) {

  var
    oOutput = document.getElementById("output"),oData = new FormData(document.forms.namedItem("fileinfo"));

  oData.append("CustomField","This is some extra data");

  var oReq = new XMLHttpRequest();
  oReq.open("POST","stash.PHP",true);
  oReq.onload = function(oEvent) {
    if (oReq.status == 200) {
      oOutput.innerHTML = "Uploaded!";
    } else {
      oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>";
    }
  };

  oReq.send(oData);
  ev.preventDefault();
},false);
原文链接:https://www.f2er.com/ajax/164940.html

猜你在找的Ajax相关文章