N
N
Nick2019-06-08 15:55:25
Yii
Nick, 2019-06-08 15:55:25

Yii2, downloading multiple files?

Please tell me how to implement the download of several files, when creating Tasks (tasks), I attach several files (2) to it, which are saved to another Files table. I need to make an actionDownload so that when the download button is clicked, both files are downloaded.
download function

public function actionDownload($id)
    {
        $data = Files::findOne($id);
        header('Content-Type:'.pathInfo($data->url,PATHINFO_EXTENSION));
        header('Content-Disposition: attachment; name='.$data->name);
        return Yii::$app->response->sendFile($data->url);
    }

create function
public function actionCreate()
    {
        $model = new Tasks();
        $performer = new Performers();
        $model2 = new Files();

        if ($model->load(Yii::$app->request->post()) && $performer->load(Yii::$app->request->post())&& $model2->load(Yii::$app->request->post()))
        {
            $model->save();
            $url = UploadedFile::getInstances($model2,'url');
            foreach($url as $file){
                $filename = uniqid();
                $model2 = new Files();
               //echo var_dump($file);
              // die();
            //   if ($file->upload()){
            if($file->saveAs(Yii::getAlias(('@webroot').'/uploads/'. $filename.'.'.pathinfo($file->name, PATHINFO_EXTENSION)))){
                $model2->id_task = $model->id;
                $model2->name = $file->name;
                $model2->url =  Yii::getAlias(('@webroot').'/uploads/'. $filename.'.'.pathinfo($file->name, PATHINFO_EXTENSION));
                $model2->save(false);
            } 
        }

            // сохраняем id Задачи в таблицу Исполнители
            $performer->id_task = $model->id;
            $performer->save();

           return $this->redirect(['view', 'id' => $model->id]);
       } else{

       return $this->render('create', [
           'model' => $model,
           'performer' => $performer,
           'model2' => $model2,
       ]);

         }
     }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sokollondon, 2020-02-11
@sokollondon

How to download multiple files in an archive

$file = \Yii::getAlias('@webroot/archive'.microtime().'.zip');
$zip = new \ZipArchive();
$zip->open($file, \ZIPARCHIVE::CREATE);
$zip->addFile("index.php");//добавляем файлы в архив
$zip->close();
if (file_exists($file)) {
    \Yii::$app->response->sendFile($file, 'archive.zip');
    ignore_user_abort(true);//удаление временного файла
    if (connection_aborted()) unlink($file);
    register_shutdown_function('unlink', $file);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question