使用Ajax和PHP上传图片 [英] Upload image with Ajax and PHP

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

问题描述

我想将图像上传到服务器,并控制HTML代码中的PHP回显.为此,我想使用jQuery Ajax,但是我不知道如何使用Ajax将图像发送到PHP.这是一个用于大学的项目,所以我不能使用任何类型的插件.

I want to upload an image to my server, and control the PHP echos in my HTML code. To do this I want to use jQuery Ajax, but I don't know how to send the image with Ajax to PHP. It's a project for college so I can't use any kind of plugin.

我的实际代码:

HTML

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file"><br>
    <input type="submit" name="submit" value="Submit">
</form>

Prueba.php

define('MB', 1048576);
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 1*MB)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("../public/images/productos/" . $_FILES["file"]["name"]))
    {
        echo $_FILES["file"]["name"] . " already exists. ";
    }
    else
    {
        move_uploaded_file($_FILES["file"]["tmp_name"],
            "../public/images/productos/" . $_FILES["file"]["name"]);
        echo "Stored in: " . "../public/images/productos/" . $_FILES["file"]["name"];
    }
}
}
else
{
echo "Invalid file";
}

我想使用这样的东西...

I want to use some like this...

JS

$(".form").submit(function(){
    $.ajax({
            url: 'core/ctrlAdmin.php?prodInBD',
            type: 'POST',
            async: false,
            data: ????
            success: function(respuesta){

                  /*   RECIVE HERE THE PHP ECHO         */

            }
    });
});

推荐答案

$(".form").submit(function(){
    $.ajax({
            url: 'core/ctrlAdmin.php?prodInBD',
            type: 'POST',
            async: false,
            data: new FormData(this);
            success: function(respuesta){

                  /*   RECIVE HERE THE PHP ECHO         */

            }
    });
});

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

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