首页 > 解决方案 > 是否可以将压缩文件夹从服务器(php)发送到前端(角度)?还是有其他方法可以做到

问题描述

我使用drupal作为后端。在 drupal 我得到一些 .pdf 文件。然后使用drupal zip archive压缩它们。然后将此存档保存在我的服务器 tmp 文件夹中,我现在使用 php sys_get_temp_dir()获取 tmp 文件夹 ...我应该返回前端(Angular)以便用户可以下载此文件夹..

这是我用于压缩的示例代码:

$nodesIds = [1024, 1023, 1022]; // those are just some example ids, i get the real ids from the front end post request.

$zipName = $this->generateUniqueName(); 
$zip = new \ZipArchive;if(!$zip->open(sys_get_temp_dir() . '/' . $zipName, constant("ZipArchive::CREATE"))) {
    return new JsonResponse('could not open zip');
}

foreach ($nodesIds as $id) {
    $node = \Drupal\node\Entity\Node::load($id);
    $uri = $node->filed_file->entity->getFileUri();
    $name = $node->field_file->entity->id() . '_'. $node->field_file->entity->getFilename();
    $url = $file_system->realpath($uri);
    $zip->addFile($url, $name);
}
$zip->close();

我尝试返回一个链接到服务器中的压缩文件夹:

return new JsonResponse(sys_get_temp_dir() . '/' . $zipName);

但我不知道如何从角度处理它。

还尝试使用 symfony返回一个流:

$stream  = new Stream(sys_get_temp_dir() . '/' . $zipName);
$response = new BinaryFileResponse($stream);

一个流而不是一个文件,因为用户选择要压缩的文件..所以他们可以选择尽可能多的..它甚至可能达到 100 个 .pdf 文件..

一切正常,我在 tmp 中获得了压缩文件夹。但现在呢?

我想将此压缩文件夹下载到用户浏览器.. 但我不知道如何!我应该返回压缩文件夹,然后以角度将其用作 blob 或以某种方式处理它并将其提供给用户,或者正确的方法是将链接发送回其在 tmp 文件夹中的位置,并在角度我只访问该位置并以某种方式获取文件夹(由于权限和安全性,我不知道这是否可能),或者还有另一种我不知道的更好方法。

非常感谢您。

标签: phpsymfonydrupalserverziparchive

解决方案


推荐阅读