在将成功/错误返回到ajax调用之前,检查文件是否存在

时间:2022-06-27 20:27:19

I'm working on a project at the moment that uses an ajax call to generate site content as a word document or pdf file for the user to download - a simplified demonstration is posted below.

我目前正在开发一个项目,该项目使用ajax调用生成网站内容作为word文档或pdf文件供用户下载——下面发布了一个简化的演示。

<?php
$errors   = array(); // array to hold validation errors
$data     = array(); // array to pass back data
// initiate array and populate only checked values
$arr      = json_decode($_POST['txtComments']);
$filetype = $_POST['filetype'];

if (!empty($errors)) {
    $data['success'] = false;
    $data['errors']  = $errors;
} else {
    $filepath = makePDF($arr);

    // check that the file has been created here....


    $data['success']  = true;
    $data['filename'] = $filepath;
}
// return all our data to an AJAX call
echo json_encode($data);


//Generate PDF file
function makePDF($comments)
{
    require_once('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial', 'B', 16);
    $pdf->Write(5, "Hello, World!\n\n\n");
    // Save File
    $file = "../tmp/" . uniqid('comments_') . ".pdf";
    $pdf->Output($file, 'F');

    // Should check that file has been created successfully here....

    return ($file);
}
?>

My question is that on the off-chance that something goes wrong with creating the file, how can I check if the file has been created, before returning either success: path_to_file, or error: error_msg? It's also worth noting that the file isn't created instantaneously - it takes a second or so to appear on the server, so I'd presume that this delay will need to be taken into account too.

我的问题是,在创建文件时出现问题的可能性很小的情况下,如何在返回success: path_to_file或error: error_msg之前检查文件是否已经创建?同样值得注意的是,该文件并不是即时创建的——在服务器上出现需要一秒左右的时间,所以我认为这一延迟也需要考虑在内。

Any suggestions, as always, are appreciated.

如有任何建议,我们都很感激。

1 个解决方案

#1


2  

You can use file_exists(filepath) PHP function. This function allows you to check if file or directory exists or not and output true or false accordingly.

可以使用file_exists(filepath) PHP函数。此函数允许您检查文件或目录是否存在,并相应地输出true或false。

#1


2  

You can use file_exists(filepath) PHP function. This function allows you to check if file or directory exists or not and output true or false accordingly.

可以使用file_exists(filepath) PHP函数。此函数允许您检查文件或目录是否存在,并相应地输出true或false。