在 Laravel 中处理加密文件(如何下载解密文件)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34624118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Working with encrypted files in Laravel (how to download decrypted file)
提问by Marcel
In my webapp, users can upload files. Before being saved and stored, the contents of the file are encrypted using something like this:
在我的 webapp 中,用户可以上传文件。在保存和存储之前,文件的内容使用如下方式加密:
Crypt::encrypt(file_get_contents($file->getRealPath()));
I then use the file system that comes with Laravel to move the file
然后我使用 Laravel 自带的文件系统来移动文件
Storage::put($filePath, $encryptedFile);
I have a table to store information about each file with columns such as:
我有一个表来存储有关每个文件的信息,其中包含以下列:
- id
- file_path
- file_name
- original_name (includes the extension)
- ID
- 文件路径
- 文档名称
- original_name(包括扩展名)
Now I want the user to be able to download this encrypted file. However, I'm having trouble decrypting the file and returning it to the user. In the file downloads response sectionof the Laravel documentation, it suggests to do this:
现在我希望用户能够下载这个加密文件。但是,我无法解密文件并将其返回给用户。在Laravel 文档的文件下载响应部分,它建议这样做:
return response()->download($pathToFile, $name, $headers);
It wants a file path which is fine, but at which point can I decrypt the file contents so that it is actually readable?
它想要一个很好的文件路径,但是在哪一点我可以解密文件内容以便它实际上是可读的?
I do seem to be able to do this:
我似乎能够做到这一点:
$encryptedContents = Storage::get($fileRecord->file_path);
$decryptedContents = Crypt::decrypt($encryptedContents);
... but I don't know how to return it as a download with a specified file name.
...但我不知道如何将它作为具有指定文件名的下载返回。
回答by Bogdan
You could manually create the response like so:
您可以像这样手动创建响应:
$encryptedContents = Storage::get($fileRecord->file_path);
$decryptedContents = Crypt::decrypt($encryptedContents);
return response()->make($decryptedContents, 200, array(
'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($decryptedContents),
'Content-Disposition' => 'attachment; filename="' . pathinfo($fileRecord->file_path, PATHINFO_BASENAME) . '"'
));
You can check out the Laravel APIfor more info on what the parameters of the make
method are. The pathinfo
function is also used to extract the filename from the path so it sends the correct filename with the response.
您可以查看Laravel API以获取有关该make
方法参数的更多信息。该pathinfo
函数还用于从路径中提取文件名,以便在响应中发送正确的文件名。
回答by gX.
Laravel 5.6 allows you to use streams for downloads: https://laravel.com/docs/5.6/responses#file-downloads
Laravel 5.6 允许您使用流进行下载:https://laravel.com/docs/5.6/responses#file-downloads
So in your case:
所以在你的情况下:
return $response()->streamDownload(function() use $decryptedContents {
echo $decryptedContents;
}, $fileName);