Вообщем ситуация такая:
есть модель, у которой есть свойство по типу это файл. В виде есть форма сделанная через ActiveForm. Нужно через ajax запрос загрузить архив. Но он не загружается (с условием, что нужно провалидейтить расширение файла, а не просто его залить).
UPDATE: Правда сейчас он стал загружаться, но валидацию не проходит.
UPDATE: При попытке получить массив $_FILES и увидеть его в консоли, появляется полностью пустой массив.
Код:
Метод
Код: Выделить всё
public function actionUploadTest()
{
$model = new \app\models\UploadForm();
if (Yii::$app->request->isAjax) {
if ($model->upload()) {
Yii::$app->session->setFlash('success', 'Файл загрузился');
return 'everything is allright!';
} else {
return 'something is gone wrong!';
}
}
return $this->render('upload-test', ['model' => $model]);
}
Код: Выделить всё
use yii\widgets\ActiveForm;
use yii\helpers\Html;
use yii\helpers\Url;
$url = Url::to();
$js = <<<JS
jQuery("form").on("submit", function(e) {
e.preventDefault();
let data = new FormData();
data.append('file', jQuery("#uploadform-file")[0].files[0]);
console.dir(jQuery("#uploadform-file")[0].files[0]);
jQuery.ajax({
url: "$url",
data: data,
method: "POST",
cache: false,
contentType: false,
processData: false,
success: function(r) {
console.log(r);
},
});
});
JS;
$this->registerJs($js);
$form = ActiveForm::begin();
echo $form->field($model, 'file')->fileInput();
echo Html::submitButton('Отправить');
ActiveForm::end();
Код: Выделить всё
namespace app\models;
use Yii;
use yii\base\Model;
/**
* UploadForm is the model behind the upload form.
*/
class UploadForm extends Model
{
public $file;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
['file', 'file', 'extensions' => '/* docx,doc,txt,xls,xlsx,pdf, */zip,7z,gz,gzip,tar,tar-gz,tgz'],
];
}
/**
* @return array customized attribute labels
*/
public function attributeLabels()
{
return [
'file' => 'Файл',
];
}
/**
* Just uploads the file
* @return bool whether upload or not
*/
public function upload()
{
if (!$this->validate()) {
return;
}
$this->file = \yii\web\UploadedFile::getInstance($this, 'file');
$this->file->saveAs('uploads/' . $this->file->baseName . time() . '.' . $this->file->extension);
return true;
}
}