创建一个临时文件夹以保持文件的结构,并通过压缩文件夹使其可下载


Create a temporary folder to keep the files in structure and make it downloadable by compressing the folder

在我的项目中,我有一些与Server上的项目相关的文件,如下所示:

Item-1  => file1.txt, file2.pdf and file3.doc
Item-2  => file4.pdf, file5.ppt
Item-3  => file6.txt, file7.docx and file8.ppt
....

我可以通过$this->getAllItems()获得以上项目,然后循环浏览每个项目。

我正在尝试以结构化的方式压缩所有这些文件。这样,用户就可以了解文件属于哪些项目。

我试图做的是将与其相关项目相关的文件保存在一个文件夹中,并将它们包装在一个"主"文件夹中(这应该发生在一个临时路径中),然后压缩它,让用户下载压缩文件夹。因此,文件将以如下所示的结构化方式:

main
   Item-1
      --> file1.txt
      --> file2.pdf
      --> file3.doc
   Item-2
      --> file4.pdf
      --> file5.ppt
   Item-3  
      --> file6.txt
      --> file7.docx
      --> file8.ppt

在这里搜索时,我得到了一个链接,它确实压缩了临时路径中的文件(,但不是文件夹),并使压缩的文件夹可以下载。

PS:用户的每个下载请求都应该进行压缩

我不确定这是否正确。。但这起到了作用。

我修改了这个链接上可用的代码的for循环部分。

# loop through each file
foreach($files as $file){
    # download file
    $download_file = file_get_contents($file);
    # Create a empty folder
    $zip->addEmptyDir($itemName);
    #add to the above created new folder in zip
    $zip->addFromString($itemName . '/' . basename($file), $download_file);
}

在上面的代码中,$itemName是在$this->getAllItems()中循环时动态获取的项目名称,正如我在文章中提到的那样。

请告诉我这是否正确。