【问题标题】:PHP/jQuery trying to send back data generated from another filePHP/jQuery 试图发回从另一个文件生成的数据
【发布时间】:2018-04-18 03:13:49
【问题描述】:

我目前正在处理一些文件,其中“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: 选择要上传的图片:

我的上传.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返回任何值,并且控制台中没有可见的错误。

【问题讨论】:

    标签: php jquery


    【解决方案1】:

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

    您还需要执行几个步骤。首先,您需要以可预测的方式专门返回 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";
            }
        }   
    
        ?>
    

    【讨论】:

    • 我尝试实现此功能,但似乎没有从 upload.php 返回任何内容,我可能没有将此代码放在正确的位置,我将编辑我的问题
    • 根据您的 PHP 版本,您可能需要使用不同的数组声明:$data = array('image' => $mediaPath);
    • 另外,打开开发者工具(尝试 F12 键)并在您发出请求时查看网络部分。您希望看到 200 的响应和一些数据。如果您看到任何其他内容,则说明 URL 有问题或处理代码有问题。 500 错误可能会返回任何错误的输出。
    • 嘿 Jamie,网络部分确实返回了 200 类型的“xhr”和 338 B 大,但是我不知道这些数据的去向?没有任何警报
    • 我刚刚注意到您编辑了您的问题,在现在的示例中,您最后有一个 return $data ,它从未正确设置,也不应该达到。此外,如果 move_uploaded_file 失败,您还会返回未设置的 $data 值;此外,为了安全起见,您应该在返回之前适当地解析或编码原始名称。还有一些其他的问题。通过在设置 $uploadOk 之前回显一个问题,对 $uploadOk 的最终检查将回显一些不会被听到的内容,然后返回一个未设置的 $data 值。
    猜你喜欢
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 2017-01-23
    相关资源
    最近更新 更多