代码之家  ›  专栏  ›  技术社区  ›  John Beasley

使用jQuery、JSON和PHP从目录中获取文件大小和文件日期

  •  0
  • John Beasley  · 技术社区  · 7 年前

    在使用jQuery、JSON和PHP成功地从目录中获取文件名之后,我现在需要能够从同一目录中获取文件大小和文件日期。

    我还没有尝试获取文件大小,但我尝试获取文件日期:

    <?php
    include('include/sessions.php'); 
    
    if(isset($_POST['editpartnercode']))
    {
       $partnerCode = $_POST['editpartnercode'];
       $bookingNum = $_POST['editbooking'];
    
       $dir = "D:/CargoDocsPDFs/". $partnerCode . "/" . $bookingNum;
    
       $ffs = scandir($dir);
    
       $files = array();
    
       foreach($ffs as $ff)
       {               
           if($ff != '.' && $ff != '..')
           {   
               array_push($files, $ff, date('F d, Y h:i A', filemtime($dir . '/' . $ff)));
           }
       }
       echo json_encode($files);
    }   
    ?>
    

    以下是显示JSON数据的jQuery:

    $.post('process/displayFiles.php', {editpartnercode:editpartnercode,editbooking:editbooking}, function(data)
    {
        var obj = JSON.parse(data);
        $('#allFiles').empty();
        var htmlToInsert = obj.map(function (item)
        {
            if(item !== '..' && item !== '.' && item !== 'Thumbs.db')
            {
                return "<form method='POST'>
                  <a href='process/viewFiles.php?img="+item+"&book="+editbooking+"' 
                  target='_blank'>"+item+"</a><br/></form>";
            }
        });
        $('#allFiles').html(htmlToInsert);      
    });
    

    (文件viewFiles.php基本上只是检查文件类型。我认为没有必要显示该代码。)

    enter image description here

    我需要在文件名旁边列出日期,而不是超链接。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Gary Thomas    7 年前

    从目录中获取文件大小和文件日期


    我需要在文件名旁边列出日期,而不是超链接。

    1.在PHP中,将循环更改为:

    foreach($ffs as $ff)
    {
        // backend file rejection rather than client (in JS) side
        if($ff != '.' && $ff != '..' && $ff != 'Thumbs.db')
        {
            $file_dir = $dir."/$ff";
    
            // Append each file information to multidimensional array
            $files[] = [
                "file_name" => $ff,
                "file_date" => date('F d, Y h:i A', filemtime($file_dir)),
                "file_size" => filesize($file_dir)
            ];
        }
    }
    

    $.post :

    try {
        var obj = JSON.parse(data);
        $('#allFiles').empty();
    
        const htmlToInsert = obj.map(item =>
            `
                <form method='POST'>
                    <a href="process/viewFiles.php?img=${item.file_name}&booking=${editbooking}" target="_blank">
                        ${item.file_name}
                    </a>
                    <span>${item.file_date}</span>
                    <span>${item.file_size}</span>
                    <br>
                </form>
            `
        );
    
        $('#allFiles').html(htmlToInsert);
    } catch (e) {
        // Throw JSON.parse exception
    }