Image upload ajax jquery

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

Im new to jQuery. I try to upload a jpg image file by using ajax method. But when I upload, it doesn't upload. Could anyone please help me to do this?

HTML

<form action="" method="POST" enctype="multipart/form-data">      <input type="file" name="image" id="image"/> </form> 

jQuery

$('#submit').click(function() {     var image=$('#image').val()          $.post("upload.php",{image:image},function(data)         {             alert(data);         });     }   }) 

PHP

<?php      $image=$_POST['image'];       $imagename=date("d-m-Y")."-".time()."jpg";      $target_path = "uploads/".$imagename;       if(move_uploaded_file($image, $target_path))       {           echo 'moved';      }      else      {           echo 'error';      } ?> 

回答1:

To upload file using ajax you must need to use FormData like below.

$("form").on('submit', (function(e) {     e.preventDefault;     var formData = new FormData(this);      $.ajax({         url : "upload.php",         type : "POST",          data : formData,         cache : false,         contentType : false,         processType : false,         success : function(data) {             alert(data);         }     }); })); 

And your PHP script should be like below.

<?php      $image=$_FILES['image'];      $image_tmp =$_FILES['image']['tmp_name'];       $imagename=date("d-m-Y")."-".time().".jpg";      $target_path = "uploads/".$imagename;       if(move_uploaded_file($image_tmp, $target_path))       {          echo 'moved';      }      else      {          echo 'error';      } ?> 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!