使用Ajax和PHP上传图像并返回上传的图像URL

时间:2013-11-05 09:44:40

标签: javascript jquery ajax

我试图上传图片而不刷新,但我对ajax知之甚少。 当我用ajax函数提交帖子时,我有php文件你的返回图片网址。

的Javascript

 $(document).ready(function() { 

        $('#photoimg').live('change', function()            { 
                   $("#preview").html('');
            $("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
        $("#imageform").ajaxForm({
                    target: '#preview'
                                       }
    }).submit();

        });
    }); 

PHP

  <?php

       $path = "uploads/";

$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
    {
        $name = $_FILES['photoimg']['name'];
        $size = $_FILES['photoimg']['size'];

        if(strlen($name))
            {
                list($txt, $ext) = explode(".", $name);
                if(in_array($ext,$valid_formats))
                {
                if($size<(1024*1024))
                    {
                        $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
                        $tmp = $_FILES['photoimg']['tmp_name'];
                        if(move_uploaded_file($tmp, $path.$actual_image_name))
                            {


                                $imge1="uploads/".$actual_image_name;
                                echo $imge1;

                            }
                        else
                            echo "failed";
                    }
                    else
                    echo "Image file size max 1 MB";                    
                    }
                    else
                    echo "Invalid file format..";   
            }

        else
            echo "Please select image..!";

        exit;
    }
        ?>

HTML

<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>

</div>
<img src = "" id="thumb_img" />

现在结果是图片网址。当图像选择ajax自动发布沙子到php.Php保存图像并返回url和这个url显示在目标div.So现在我需要这个url设置为背景url。像图像选择target div背景更改。

1 个答案:

答案 0 :(得分:1)

我会做类似的事情:

$('#myForm').ajaxForm(function(url) { 
   $('#preview').css('background-image', "url(" + url + ")"); 
});