S
S
skajtersen2017-05-26 09:31:00
Yii
skajtersen, 2017-05-26 09:31:00

How to make file upload from console?

There is a controller to process the file.

public function actionIndex()
    {
        $model = new Logs();
        $filename = new UploadHistory();

        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, 'file');
            if ($model->file && $model->validate()) {
                $model->file->saveAs($model->file);
                $filename->filename = $model->file->name;
                $filename->save();
                $path = $filename->filename_id;
                $rows = $model->indexFile($model->file);
                $model->logUpload($rows, $path);
            }
        }

        return $this->render('index', ['model' => $model]);
    }

How to correctly rewrite it to the /commands folder to call this command from the command line. That is interested in how to transfer the file in this case.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
Evgeny Bukharev, 2017-05-26
@evgenybuckharev

I wonder why you need to pass the file to the script from the console?)

K
Kirill Petrov, 2017-05-26
@Recosh

If you want to transfer exactly the body of the file, then pack it in base64 for example and shove it as a parameter. And in php, parse the parameter and translate it into a file stream.

M
Maxim Fedorov, 2017-05-26
@qonand

You won't be able to do this by standard means and, accordingly, using the code you provided will also fail. Therefore, you need to write your own class for uploading files (ala UploadedFile) that implements the functionality you need

I
Ivan Koryukov, 2017-05-27
@MadridianFox

Because you call the command from the console, it is obvious that the file must already be on the server.
By calling the command, we can simply pass it the path to the file, and then, having this path, we can open the file and do something with it using standard functions (well, or wrap it in some convenient object).

public function actionIndex($filepath){
   $filename = end(explode('/',$filepath));

   $file_handler = fopen($filepath); // далее используем дескриптор файла для чтения/записи
   // или
   $file_content_string = file_get_contents($filepath); // сразу читаем содержимое в строку
}

You need to call this case like this:php yii MyCommand /path/to/file

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question