Answer the question
In order to leave comments, you need to log in
How to save data with file upload in YII2?
Installed a widget for downloading files from Kartik. But in parallel with loading the file, it is necessary to save the data in the database.
But something doesn't work for me.
Here is the model:
class UploadFiles extends Model
{
/**
* @var UploadedFile[]
*/
public $dataFiles;
public $filePath;
public $class;
public function __construct()
{
$this->filePath='uploads_files/';
}
public function rules()
{
return [
[['class'],'string'],
[['dataFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'txt, csv', 'maxFiles' => 4,'checkExtensionByMimeType' => false],
];
}
public function upload()
{
if ($this->validate()) {
foreach ($this->dataFiles as $file) {
$file->saveAs($this->filePath . $file->baseName . '.' . $file->extension);
if(ImportFile::findOne(['file'=>$file->baseName])){
return false;
}else{
$model_file=new ImportFile();
$model_file->file=$file->baseName;
$model_file->url=$file->extension;
$model_file->path=$this->filePath;
$model_file->integrity=0;
$model_file->class=$this->class;
$model_file->save();
}
}
return true;
} else {
return false;
}
}
}
$model=new \app\models\UploadFiles();
$form = ActiveForm::begin(['action' => ['/laboratory/flash-analizator/upload'],'options' => ['enctype' => 'multipart/form-data']]);
echo $form->field($model, 'class')->widget(Select2::classname(), [
'data' =>['сlass_1'=>"Обработчик 1",'class_2'=>"Обработчик 2"],
'options' => ['placeholder' => 'Select a state ...'],
'name' => 'class',
'pluginOptions' => [
'allowClear' => true
],
]);
echo $form->field($model, 'dataFiles')->label('Выбранный файл')->widget(FileInput::classname(),[
'id'=>'file',
'name' => 'file-input',
'disabled' => false,
'language' => 'ru',
'pluginOptions' => [
'uploadUrl' => Url::to(['/laboratory/flash-analizator/upload']),
'showPreview' => false,
],
]);
ActiveForm::end();
public function actionUpload()
{
if(Yii::$app->request->isPost){
$model = new UploadFiles();
$model->load(Yii::$app->request->post());
$model->dataFiles = UploadedFile::getInstances($model, 'dataFiles');
if ($model->upload()) {
return true;
}else{
return Json::encode([
'error' => 'Ошибка загрузки файла'
]);
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question