繁体   English   中英

如何从 sql 数据库中的单个单元格下载多个文件? 我正在使用 laravel 5.5

[英]how to download multiple files from a single cell in sql database? I am using laravel 5.5

我有一个包含员工详细信息的用户行,并且 $image 有多个文件存储在数据库中。 我想下载每个文件。 到目前为止,我只能下载存储在 $image 中的单个文件

这是myview.blade.php

<input type="file" name="image[]" class="form-control" value="{{ $employee['image'] }}" multiple>
 <a href="{{ url('/people/employees/download/' . $employee['image']) }}">{{$employee['image']}}</a>

我的route.php

Route::get('/people/employees/upload/{id}', 'EmplController@upload');
Route::get('/people/employees/download/{image}', 'EmplController@download');

我的controller.php

public function test(Request $request, $id) {
    
    $employee = User::find($id);

    if($request->hasfile('image')){
        $files = [];
        foreach ($request->image as $image) {
            $path = $image->getClientOriginalName();
            $filename = time() . '-' . $path;
            $files[] = $filename;
            $image->storeAs('employees', $employee->id . '/' . $filename);
            $image->move(public_path('employees'),$filename);
        }

        $files = explode(",", $files[0]);
    }

    $employee->image = $employee->image  .  $files[0];
    $employee->save();  
}

public function download($image){
    $employee = User::find($image);
    $filename = $image;
    $filepath = public_path('employees/' . $filename);

    return response()->download($filepath);
}

当我在上传多个文件时执行 print_r function 时会选择一个文件?

Array ( [0] => 1596838646-logo.jpg )

我想下载 myview.blade 上显示的多个文件。

我相信您要问的是使用 HTTP 协议通过同一请求下载多个文件,这是不可能的,因为它在这个答案中解释:

Laravel 下载多个文件

我的建议是制作一个客户端 function 可以对每个特定文件的下载方法进行多次调用。

例如,根据您的问题,可能类似于:

HTML:

<a onclick='return downloadFiles()'>{{$employee['image']}}</a>

JS:

function downloadFiles(e) {
    e.preventDefault();
    for (img of IMAGES_FROM_THE_BACK) { 
        setTimeout(() => {
            window.open(`/people/employees/download/${img}`);
        }, 300);
    }
});

请注意,您需要将图像从后到前端传递到数组或 object 中,这样您就有了 HTML。

正如上面的子操作所说,这是不可能的,因为 HTTP 不支持多个文件下载。 解决方案之一是打开每个文件的连接以下载,但在我看来,更优雅的是文件压缩,它包含所有文件。

PHP 提供了解决方案,它是ZipArchive

之后,您 ZIP 所有文件,写入磁盘的 tmp 目录中,并使用您的文件位置发送 stream 响应。 在 php 关闭连接后,您可以使用Laravel 终止中间件/回调并删除该存档以刷新磁盘上的空间。

从上面的链接中获取的普通 PHP 中的简单示例。

$files = array('image.jpeg','text.txt','music.wav');
$zipname = 'enter_any_name_for_the_zipped_file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
  $zip->addFile($file);
}
$zip->close();

///Then download the zipped file.
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM