【问题标题】:Download button in Laravel with multiple documents ID's on buttonLaravel 中的下载按钮,按钮上有多个文档 ID
【发布时间】:2017-12-23 09:56:33
【问题描述】:

我的查询以逗号分隔值从数据库返回结果:1,2,3..etc 然后我正在尝试制作一个下载按钮,并且应该选择 1 个或多个要下载的文档(基于 if 是 1 个 id 还是多个)。

所以一个文件的按钮看起来像这样

<a href="users/files/download/2?_token=SivFIl3kKuflAvIyYJFGKdovJHTlqpjObN2nMFbQ">Download Now</a>

查询返回多个 id 的按钮如下所示(注意令牌前的 2,3

<a href="users/files/download/2,3?_token=SivFIl3kKuflAvIyYJFGKdovJHTlqpjObN2nMFbQ">Download Now</a>

这是我添加到 routes.php 中的

Route::get('/users/files/download/{fileId}', 'UsersController@getDownload');

这个给控制器

public function getDownload($fileId)
{
    $file = Documents::findOrFail($fileId);
    $file = public_path(). "/uploads/" . $file->document_path;
    return Response::download($file, 'filename.pdf');
}

目前无论我点击哪个按钮我都有

Illuminate\Database\Eloquent\ModelNotFoundException: 没有模型 [Documents] 的查询结果。

这是什么意思?模型在那里。这是文档模型

class Documents extends Eloquent
{
    protected $table = 'documents';
    protected $primaryKey = 'id';
    public $timestamps = false;
}

当文档 ID 为多个时,如何选择所有文档 ID?

更新:当前代码

$file = Documents::findOrFail([$fileId]);

$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name,  ZipArchive::CREATE);
    foreach ($file as $files) {
    $path = public_path(). "/uploads/" . $files['document_path'];

        if(file_exists($path)){
            $zip->addFromString(basename($path),  file_get_contents($path));
        }
        else{ echo"file does not exist"; }                  
    }
 $zip->close();

【问题讨论】:

  • 在 laravel 中不能一次下载多个文件,但你可以将这些文件创建一个 zip 文件并下载

标签: php laravel laravel-4


【解决方案1】:

您需要在一个数组中传递$fileId 以获得多个id

$file = Documents::findOrFail([$fileId]);
$number_of_files = count($file);
if ($number_of_files > 1) {
    // Push all the files in a zip and send the zip as download
} else {
   // Send the file as a download
   $file = public_path(). "/uploads/" . $file->document_path;
   return Response::download($file, 'filename.pdf');
}

【讨论】:

  • 嗯,现在我收到ErrorException: Undefined index: document_path。如果我 dd($file) 我看到 document_path 存在
  • 可能您得到的结果不止一个。在这种情况下,您需要遍历$file
  • 是的,我得到 1+ 结果,因为 ID 是 1+。循环到哪里?在控制器内部以及如何将其传递给下载?
  • 我添加了一个循环,但只下载一个文件而不是多个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 2012-12-01
  • 2017-07-10
  • 2019-12-29
  • 2016-11-23
  • 2019-10-30
相关资源
最近更新 更多