実現したい機能
複数ファイルをZip化してダウンロードする機能を実装したいです。または、Zip化せずに複数ダウンロード機能を実装したいです。
やり方や参考になる記事をご存知でしたら教えていただけると助かります????♂️
試したこと
※全てCakePHPを使用して実装しています。
①foreach
すでに1つずつのファイルダウンロード機能が実装できているので、foreachで処理を回す。処理は1回目のダウンロード時に終わってしまいますのでこのやり方はできませんでした。
php
1 if ($this->request->is(['patch', 'post', 'put'])) { 2 $data = $this->request->data; 3 $result = $this->Common->download($data['dl']); 4 if ($result['error'] == true) { 5 $this->Flash->error($result['message']); 6 return $this->redirect([]); 7 } 8 } 9 10 public function download($file_pass = '') 11 { 12 $params = [ 13 'Bucket' => S3_BUCKET_NAME, 14 'Key' => $file_pass 15 ]; 16 $file_name = str_replace('user_upload/', '', $file_pass); 17 18 $s3 = new S3Client([ 19 'credentials' => [ 20 'key' => S3_ACCESS_KEY, 21 'secret' => S3_SECRET_KEY 22 ], 23 'region' => S3_BUCKET_REGION, 24 'version' => 'latest' 25 ]); 26 27 try { 28 $result = $s3->getObject($params); 29 $len = $result['ContentLength']; 30 header('Content-Type: application/force-download;'); 31 header('Content-Length: '.$len); 32 header('Content-Disposition: attachment; filename= '.$file_name); 33 echo $result['Body']; 34 return; 35 } catch(S3Exception $e) { 36 $return = [ 37 'error' => true, 38 'message' => 'ダウンロードに失敗しました。' 39 ]; 40 return $return; 41 } 42 }
②記事を参考に
php
1]header('Content-Type: application/octet-stream'); 2header('Content-disposition: attachment; filename="file.zip"'); 3 4require "./aws.phar"; 5use Aws\S3\S3Client; 6 7$bucket = 'myBucket'; 8 9$client = S3Client::factory(array( 10 'key' => getenv('AWS_ACCESS_KEY_ID'), 11 'secret' => getenv('AWS_SECRET_KEY') 12)); 13 14$result = $client->getObject(array( 15 'Bucket' => $bucket, 16 'Key' => 'test.txt', 17 'SaveAs' => '/tmp/test.txt' 18)); 19 20$Uri = $result['Body']->getUri(); 21 22$fp = popen('zip -r - '.$Uri, 'r'); 23 24$bufsize = 8192; 25$buff = ''; 26while( !feof($fp) ) { 27 $buff = fread($fp, $bufsize); 28 echo $buff; 29} 30pclose($fp);
③ライブラリ
このライブラリで実現できるか検証しましたが、返り値がバイナリデータで上手く動作しませんでした。
何か方法やアイディアある方は教えていただけると助かります????♂️
参考にした記事
回答1件
あなたの回答
tips
プレビュー