使用AJAX和FormData将多个文件上载到WordPress

时间:2016-12-15 13:10:12

标签: wordpress

我正在运行WordPress 4.5.4。我正在使用AJAX和FormData将文件上传到WordPress。如何在单个AJAX请求中上传多个文件?

这是我的代码:

<input type="file" name="file" id="file">
<input type="file" name="file2" id="file2">
<input type="submit" id="submit" name="Upload" onclick="upload();return false;">

<script type="text/javascript">
function upload(){
  var formData = new FormData();
  formData.append("action", "upload-attachment");

  var fileInputElement = document.getElementById("file");
  formData.append("async-upload", fileInputElement.files[0]);
  formData.append("name", fileInputElement.files[0].name);

  <?php $my_nonce = wp_create_nonce('media-form'); ?>
  formData.append("_wpnonce", "<?php echo $my_nonce; ?>");
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange=function(){
    if (xhr.readyState==4 && xhr.status==200){
      console.log(xhr.responseText);
    }
  }
  xhr.open("POST","/wp-admin/async-upload.php",true);
  xhr.send(formData);
}
</script>

0 个答案:

没有答案