文件下载在Laravel 5中不起作用?

时间:2018-01-20 05:39:28

标签: php laravel file laravel-5 download

我已在/public/storage/attachment中存储了一个文件,该文件有一个hashname,该文件存储在我的数据库以及attachmentsfilehashname列中

public/attachment/N52lbwmzubAcgUfHYhCC4A6NFBniIVmK.pdf

在视图中我将文件显示为链接,以便当用户单击链接时文件被下载。

<a href="{{ URL::to( '/download/'.$post->attachments[0]->filehashname) }}">
   {{ $post->attachments[0]->filename }}
</a>

web.php

Route::get('/download/{filehashname}', 'PostController@downloadAttachment');

PostController中

public function downloadAttachment($filehashname)
    {
        $file= public_path('/storage/attachment/'.$filehashname);

        return response()->download($file, 'demo.pdf');
    }

但是,这不会下载文件,而是使用http://localhost:8000/download/public/attachment/N52lbwmzubAcgUfHYhCC4A6NFBniIVmKfctqMNOq.pdf

打开网址Page Not Found

如果我对文件名进行硬编码并单击该链接然后下载,但在url中动态传递文件名称会显示Page Not Found错误。

如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

试试这个

while (any(is.na(group_df$id_group))) {
  group_df <<- group_df %>%
    mutate(
      id_group = ifelse(
        is.na(id_group),
        group_df$id_group[match(prev_id, group_df$id)],
        id_group))
}

group_df
#>   id prev_id id_group
#> 1 35      10        1
#> 2  4       3        1
#> 3  3      NA        1
#> 4  9       5        2
#> 5  5      NA        2
#> 6 17      NA        3
#> 7 11       8        4
#> 8 10       4        1
#> 9  8      NA        4

public_path()

答案 1 :(得分:0)

如果您的文件存储在公共目录中,请尝试 public_path(),如果您的文件保存在存储目录中,请尝试 storage_path()

$destination = storage_path('storage/attachment/'); // if your storage folder contains only attachement folder then like this :- storage_path('attachment/');
               or
$destination = public_path('storage/attachment/');
$pathToFile = $destination.$filehashname;
return response()->download($pathToFile,'demo.pdf');

希望有所帮助:)

答案 2 :(得分:0)

您只需在锚标记

中添加downlaod选项即可
<a href="{{ URL::to( '/download/'.$post->attachments[0]->filehashname) }}" download >
 {{ $post->attachments[0]->filename }}
</a>

正在回答here