weixin_33713503 2015-12-12 05:05 采纳率: 0%
浏览 26

图片上传ajax jquery

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条回答 默认 最新

  • weixin_33744141 2015-12-12 05:55
    关注

    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';
         }
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 chipyard环境搭建问题
  • ¥20 matlab可以把多个二维图合成为三维瀑布图吗
  • ¥15 EEPROM,软件i2c
  • ¥500 求解读该段JS代码,需要知道是用干什么的
  • ¥20 qt4代码实现二进制文件读取显示,以及显示的内容进行搜索
  • ¥15 Labview获取LK-G3001数据
  • ¥15 我知道什么是混合树,但是怎么写代码啊
  • ¥50 开发板linux系统安装dpkg,apt函数库 有偿
  • ¥15 浏览器时间循环 交互事件和延时事件的 优先级与执行问题
  • ¥15 GD模块安装出错,libgd无法正常安装