Php,Jquery文件为什么$ _files []为空?

时间:2016-02-05 11:13:14

标签: javascript php jquery ajax

我试图使用php和jquery制作图片上传器,但我无法让它工作。
我的问题是 为什么是$ _FILES [' image'];空?
继承我的代码

HTML
的index.php

 <form id="uploadForm" action="" method="post">
 <input name="image" type="file" id="image" />
 <a href="#" id="uploadforms">Upload</a>
 </form>
 <div id="uploadresult"></div>

的jQuery
javascript.js

  function uploadimages(){
   $.ajax({
      type: 'POST',
      url: '../ajax/upload.php',
      processData: false,
      contentType: false,
      cache: false,
      data: new FormData(this),
       success: function (data) {
         $("#uploadresult").html(data);
       },
    });
  }
  $("#uploadforms").click(function(){
    uploadimages();
  });


upload.php的

 <?php
 if(!empty($_FILES['image'])) {
     echo "Upload image";
 }
 else{
     echo "Error";
 }
 ?>

1 个答案:

答案 0 :(得分:2)

您忘记了表单中的enctype='multipart/form-data' 像这样

 <form id="uploadForm" action="" method="post" enctype="multipart/form-data">

如需更多信息,请点击herehere

更新

从函数调用传递表单

 $("#uploadforms").click(function(){
    var form = $('form')[0]; //access form obj
    uploadimages(form);
  });

并以

的形式访问它
function uploadimages(formObj){
   $.ajax({
      type: 'POST',
      url: '../ajax/upload.php',
      processData: false,
      contentType: false,
      cache: false,
      data: new FormData(formObj), //changes here
       success: function (data) {
         $("#uploadresult").html(data);
       },
    });
  }