0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravelでs3から落としてきたデータをストリーミングでクライアントへ返す方法

Posted at

初めに

これは備忘録なので、日本語で理解しずらい部分もあるかもしれません。
その点ご了承ください。

開発環境

Laravel 6.0
homestead
vagrant

はじまり

ajaxでs3にあるデータをzipファイルにして落とそうと思ってたんだけど、どうしても一度内部でzipファイルを保存してから

Storage::disk('public')->download($zipFileName);

こんな感じでクライアントへresponseするしかやり方が分からなかった。
ただ、毎回こんな風にzipファイルを内部に保存してたら、いろいろ面倒だなーということでストリーミングでダウンロードできるようにする方法を模索し始めたのが今回のお話

結局何使ったの?

最終的にはstechstudio/laravel-zipstream
のパッケージを使った。内部ではmaennchen / ZipStream-PHPこれをつかってるらしい。

これを使うのはいいものの、どの記事でもs3から複数のデータをzip化する方法が書いてなくて、そこでつまずいた。

最終的には

$zip = Zip::create('sample.zip');

            if (File::where('project_id', $id)->exists()) {
                $downloadFileArray = File::select(['XXXX', 'XXXX'])->where('id', $id)->get();
                $a = 1;
                foreach ($downloadFileArray as $fileInfo) {
                    $contents = Storage::disk('s3')->get($fileInfo->file_path);
                    $fileName = $fileInfo->file_name;
                    $extension = \File::extension($fileName);
                    $zip->addRaw($contents, $a.".".$extension);
                    $a++;
                }

            }
            return $zip;

こんな感じになった。
サンプルでよくあるのは

Zip::create("package.zip")
    ->addRaw("...file contents...", "hello.txt");

こんなやつだけど、分離して書けばいいだけでしたね。

あともう一個躓いてるのは、ファイル名の日本語化が出来ないこと
これに気づかなくて、すっごい躓いた。

どうにかして日本語化できないかなー。
だれか知ってる人教えてー

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?