PHP/jQuery 尝试发回从另一个文件生成的数据

标签 php jquery

我目前正在处理一些文件,其中“fileA.php”有一个选项(除其他外)将图像上传到我的服务器。 “上传图像”按钮调用“upload.php”以确保它符合我所需的参数,上传图像,生成随机名称,然后将图像重命名为随机名称。

我希望能够从 upload.php 将图像的新名称返回到 fileA.php,这样我就可以为用户提供某种弹出窗口或消息:

“您的图片已成功上传并重命名为 xyz.jpg”

我目前正在使用 jQuery 和 PHP POST 的组合在文件之间发送数据。我看过很多帖子,其中的答案似乎是“从 upload.php 中回显您想要的数据,然后要求 fileA.php 中的上传文件”,但我无法让它工作,并且我希望返回upload.php 中生成的随机文件名保存在 fileA.php 的变量中

各位,我运气不好吗?感谢您的阅读。

在“upload.php”文件末尾的以下代码中,我想将 $mediaPath 的值返回到 fileA.php

if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {


    $randName = substr(md5(rand()), 0, 15) . '.' . $imageFileType; //generates a pseudorandom string 2^31(? I think so, also saw 2^32 somewhere, but how?) possibilities, as the md5 hash of a random int truncated to 15 characters


    rename($target_file, "/var/www/html/uploads/" . $randName);

    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded and renamed to <new name here>";
} else {
    echo "Sorry, there was an error uploading your file.";
}
}

$mediaPath = "/var/www/html/uploads/" . $randName;

return $mediaPath;

然后我想我需要在“fileA.php”中实现某种 jQuery 函数,如下所示:

 $.ajax({
 type: "POST",
 url: "upload.php",
 datatype: "html",
 data: dataString,
 success: function(data) {
   alert(data);
   }
});

这可以获取“$mediaPath”的值并提醒我——到目前为止,这并没有给我任何将插入到文件中的“数据”值,它只是输出通用语句硬编码到 upload.php 中?

继续尝试,很想最终破获这个案子!欢迎所有关于如何做到这一点/最佳实践的合理建议,干杯。

编辑 - 尝试更新以包含 Jamie M 的答案:

我的 jQuery:

    $(document).ready(function() { 
        $('#imageForm').ajaxForm(function() { 
              $.ajax({
                   type: "POST",
                   url: "upload.php",
                   dataType: "json", // We want a JSON response
                   data: dataString, // I have to assume this is already set by the upload utility
                   success: function(data) {
                     alert(data.image); // Specify the index
                   }
            });
        }); 
    });

</script>

我的 HTML/PHP: 选择要上传的图片:

我的upload.php

header('Content-type: application/json'); // Tell the browser what to expect so it can handle it properly



$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Grabs the file extension of the submitted file, to be used on/around line 28
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Checks uploads/ to see if file already exists, throws uploadOk to 0 therefore sending an error if it does. This is probably going to be made useless by randomizing the upload names. Also what if two people want to use the same picture?
 if (file_exists($target_file)) {
    echo "Sorry, file already exists. \n";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 2000000) {
    echo "Sorry, your file is too large. \n";
    $uploadOk = 0;
}
// Allow certain file formats, checks to make sure it is a valid image 
format using $imageFileType
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed. \n";
    $uploadOk = 0;
 }









// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded. \n";
// if everything is ok, try to upload file
} else {
     if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], 
$target_file)) {


    $randName = substr(md5(rand()), 0, 15) . '.' . $imageFileType; 
//generates a pseudorandom string 2^31(? I think so, also saw 2^32 somewhere, but how?) possibilities, as the md5 hash of a random int truncated to 15 characters


        rename($target_file, "/var/www/html/uploads/" . $randName);
        $data = ['image' => $randName]; // You can add as many items as you like here
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded and renamed to <new name here>";
    } else {
         echo json_encode($data);
    }
}

    echo json_encode($data); // Encode it properly to ensure the response is valid for browser parsing


?>

到目前为止,我没有成功,上面的代码(似乎)没有从 upload.php 返回任何值,并且控制台中没有可见的错误。

最佳答案

我希望我正确理解了你的问题..

这里您还需要执行几个步骤。首先,您需要以可预测的方式专门返回 JSON 数据。为此,我建议在 upload.php 中执行以下操作:

$data = ['image' => $mediaPath]; // You can add as many items as you like here
header('Content-type: application/json'); // Tell the browser what to expect so it can handle it properly
echo json_encode($data); // Encode it properly to ensure the response is valid for browser parsing
exit(); // Optional, but nothing beyond this point can be properly returned.

JSON 期望数据被回显,而不是返回,并且通过在数组中建立索引,可以在下一步中轻松访问(在 fileA.php 中):

<script type="text/javascript">
  $.ajax({
   type: "POST",
   url: "upload.php",
   dataType: "json", // We want a JSON response
   data: dataString, // I have to assume this is already set by the upload utility
   success: function(data) {
     alert(data.image); // Specify the index
   }
  });
</script>

这应该可行,然后您只需对 data.image 进行您喜欢的操作即可。

编辑

您编辑的处理代码中存在许多缺陷,我(很快,但不是完美地)尝试在下面解决一些缺陷。不清楚的一件事是,在成功处理的情况下,您的上传工具期望看到什么 - 可能是您生成的响应正在破坏它。

无论如何,请尝试以下操作:

<?php

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = true;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

    $errorMsgs = array();

    // Grabs the file extension of the submitted file, to be used later
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check === false) {
            $errMsgs[] = "File is not an image.";
            $uploadOk = false;
        }
    } else {
        // What are we doing here?
    }

    // Checks uploads/ to see if file already exists, throws uploadOk to 0 therefore sending an error if it does. This is probably going to be made useless by randomizing the upload names. Also what if two people want to use the same picture?
    if (file_exists($target_file)) {
        // NOTE: we don't echo yet as this would break any subsequent output
        $errMsgs[] = "Sorry, file already exists. \n";
        $uploadOk = false;
    }

    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 2000000) {
        $$errMsgs[] = "Sorry, your file is too large. \n";
        $uploadOk = false;
    }

    // Allow certain file formats, checks to make sure it is a valid image format using $imageFileType
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
      && $imageFileType != "gif" ) {
        $$errMsgs[] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed. \n";
        $uploadOk = false;
     }

    // Check if $uploadOk has been negated
    if (!$uploadOk) {
        // Set header for browser to understand
        header('Content-type: application/json');
        echo implode(', ', $errMsgs);
        exit();

    } else {
         if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            $randName = substr(md5(rand()), 0, 15) . '.' . $imageFileType; 
            //generates a pseudorandom string 2^31(? I think so, also saw 2^32 somewhere, but how?) possibilities, as the md5 hash of a random int truncated to 15 characters

            rename($target_file, "/var/www/html/uploads/" . $randName); // What if this fails?

            $data = array(
                'success' => 1,
                'image' => $randName,
                'message' => "The file " . basename( $_FILES["fileToUpload"]["name"]) . " has been uploaded and renamed to {$randName}"
            ); 
            // You can add as many items as you like above. NOTE you can now use data.image for the image name or data.message for the full string.

            // NOTE: What is the uploader expecting to receive in case of success?

            header('Content-type: application/json');
            echo json_encode($data); // This was probably your main issue

        } else {
            header('Content-type: application/json');
            echo "Unable to store file in system";
        }
    }   

    ?>

关于PHP/jQuery 尝试发回从另一个文件生成的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49890570/

相关文章:

php - 如何使用php Youtube Api获取所有用户订阅?

php - Mysql搜索以逗号分隔的字符串

javascript - 将鼠标悬停在另一个 div 上时定位特定 div

Jquery - 将元素文本存储在变量中以便在更改后进行访问

javascript - 使用 jquery 检查文本可见性。包含代码未按预期运行

php - 如何使用ajax从mysql数据库中选择月份和年份

javascript - 如何将选定产品的行及其数量保存到 MySQL 数据库?

php - 带有Where子句的CodeIgniter Select语句

javascript - 将 jquery 调用发送到外部 url

javascript - 动画功能 : change div width by using radio buttons