来自zip的文件响应

时间:2014-08-03 15:40:00

标签: php file zip response

这就是我要做的事情:我使用ZipArchive类创建了zip存档,其中包含多个文件,我现在需要做什么,打开存档,读取单个文件并下载或打开它在浏览器中。

由于我使用的是symfony2框架,如果是常规文件,我可以这样做:

case 'open':
    $response = new BinaryFileResponse($filepath);
    $response->headers->set('Content-type', mime_content_type($filepath));
    $response->setContentDisposition(
        ResponseHeaderBag::DISPOSITION_INLINE,
        $filename
    );
    return $response;
case 'save':
    $response = new BinaryFileResponse($filepath);
    $response->headers->set('Content-type', mime_content_type($filepath));
    $response->setContentDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT,
        $filename
    );
    return $response;

但由于文件不在任何目录中,我可以将其传递给BinaryFileResponse类,因为它只接受文件或SplFileInfo对象的字符串路径,而不接受文件内容。

我发现以下post让我想到从文件内容创建SplFileObject,然后将它作为SplFileInfo对象传递给BinaryFileResponse类,因为SplFileObject扩展了SplFileInfo,所以这就是我所做的:

$tmp = 'php://temp';
$file = new \SplFileObject($tmp, 'w+');
$file->fwrite($filecontents);

然后将$ file传递给BinaryFileResponse类,但它抛出错误:文件" php:// temp"不存在。我不知道我是否正确地做了这样的事情,如果是的话,我错过了什么。

无论如何,我要实现的目的是以两种不同的方式提供存档文件:1。下载,2。在浏览器中打开。

PS。这些文件是PDF格式。如果我创建响应对象并将其内容设置为归档文件的内容,我可以打开它们,但是我无法直接下载它。

很抱歉,如果它令人困惑,并提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

What I eventually came up with:

//1. Extract file to chosen directory
$zip = new \ZipArchive();
if ($zip->open('file/path/file.zip') {
    $zip->extractTo('chosen/directory', array('filename_in_zip_archive.ext'));
    $zip->close();
}

//2. Put file in response
$response = new Response(file_get_contents('chosen/directory/filename_in_zip_archive.ext'));
$mime = new \finfo(FILEINFO_MIME_TYPE);
$response->headers->set('Content-type', $mime->file('chosen/directory/filename_in_zip_archive.ext'));

//3. logic to open or download file
case 'open':
    $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, 'filename_in_zip_archive.ext');
case 'save': 
    $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'filename_in_zip_archive.ext');


//4. After file has been put to response, delete local file copy
if (file_exists('chosen/directory/filename_in_zip_archive.ext')) {
    unlink('chosen/directory/filename_in_zip_archive.ext');
}

//5. Return response with file
return $response;
相关问题