什么是http头,什么时候我需要指定它们


What are http headers and when do I need to specify them

我正在尝试用laravel下载文件。我看到了很多例子,显示了标题数组的东西链接内容类型/大小等。

我的问题是这些标题是什么,什么时候我需要设置它们

我的代码示例:
$file_path = public_path() . 'path/to/file' . $file_name;
        if (file_exists($file_path)) {
            return response()->download($file_path, $file_name);
        }

这对我有用。但是我已经看到一些例子添加一个标题数组作为第三个参数,我很好奇知道它的使用。

谢谢

HTTP报头为你的浏览器提供了关于它从请求中得到的响应的额外信息。在您的示例中,Content-type标头向浏览器提供了有关服务器返回的内容类型的信息(信不信由您)。通过指定Content-type: application/pdf,浏览器将知道它必须使用adobereader插件来显示服务器返回的内容。你可以在这篇维基百科文章中找到更多关于HTTP报头的信息。

你可以在你的Laravel应用程序中像这样使用HTTP响应头:

return new 'Illuminate'Http'Response(file_path, 200, [
            'Content-type' =>  'application/pdf',
            'Content-Disposition' => 'attachment; filename=' . $file_name,
]);

像这样:

return new 'Illuminate'Http'Response($file_path, 200, [
            'Content-type' =>  'application/pdf',
            'Content-Disposition' => 'attachment; filename=' . $file_name,
        ]);

通过这种方式,我们传递正确的报头,然后响应将处理客户端的返回