在Laravel中处理加密文件(如何下载解密的文件) [英] Working with encrypted files in Laravel (how to download decrypted file)

查看:328
本文介绍了在Laravel中处理加密文件(如何下载解密的文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的webapp中,用户可以上传文件。在保存和存储之前,文件的内容使用以下方式加密:

In my webapp, users can upload files. Before being saved and stored, the contents of the file are encrypted using something like this:

Crypt::encrypt(file_get_contents($file->getRealPath()));

然后我使用Laravel附带的文件系统移动文件

I then use the file system that comes with Laravel to move the file

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(包括扩展名)

  • id
  • file_path
  • file_name
  • original_name (includes the extension)

现在我希望用户能够下载此加密文件。但是,我无法解密文件并将其返回给用户。在Laravel文档的文件下载回复部分中,它建议这样做:

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 section of the Laravel documentation, it suggests to do this:

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?

我似乎可以这样做:

$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.

推荐答案

您可以手动创建响应:

$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) . '"'
));

您可以查看 Laravel API ,了解更多关于使方法的参数是什么的信息。 pathinfo 功能是也用于从路径中提取文件名,以便它发送正确的文件名与响应。

You can check out the Laravel API for 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中处理加密文件(如何下载解密的文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆