图片上传ajax jquery [英] Image upload ajax jquery

查看:160
本文介绍了图片上传ajax jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jQuery的新手。我尝试使用ajax方法上传jpg图像文件。但是当我上传时,它不会上传。有人可以帮我这么做吗?

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


推荐答案

使用 ajax上传文件您必须使用 FormData ,如下所示。

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);
        }
    });
}));

您的 PHP 脚本应如下所示。

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

这篇关于图片上传ajax jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆