我不确定这是一个新的bug还是发生了什么,但是我很难让Yii2验证器在上传文件后识别文件.客户端验证工作正常.
模型规则:
return [
[['store_id', 'name', 'csv'], 'required'],
[['store_id', 'created_at', 'updated_at'], 'integer'],
[['name'], 'string', 'max' => 255],
[['csv'], 'file', 'skipOnEmpty' => false, 'maxSize'=>1024 * 1024 * 2],
];
Run Code Online (Sandbox Code Playgroud)
控制器动作:
public function actionUploadFromCsv()
{
$store = Yii::$app->user->identity->store;
$store_csv = new StoreCsv;
$store_csv->store_id = $store->id;
$store_csv->name = $store_csv->getDefaultName();
if (Yii::$app->request->isPost) {
$store_csv->csv = UploadedFile::getInstance($store_csv, 'csv');
if ($store_csv->upload()) {
return $this->redirect(['view-csv', 'id'=>$store_csv->id]);
}
return json_encode($store_csv->getErrors());
}
return $this->render('csv_upload', [
'store'=>$store,
'csv'=>$store_csv
]);
}
Run Code Online (Sandbox Code Playgroud)
模型上传()功能:
public function upload()
{
if ($this->validate()) {
$file_name = uniqid(rand(), false) . '.' . $this->csv->extension;
$this->csv->saveAs(Yii::getAlias('@backend') . '/web/store/' . $this->store_id . '/csv/' . $file_name);
$this->csv = $file_name;
return $this->save();
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
表格标记:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($csv, 'csv')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
Run Code Online (Sandbox Code Playgroud)
目前,当我执行上传时,验证失败后会出现此错误:
{"csv":["Please upload a file."]}
Run Code Online (Sandbox Code Playgroud)
但是,如果我将'skipOnEmpty'更改为true,它可以正常工作.它保存模型并移动和重命名临时文件.我想让验证工作,所以我可以限制某些扩展.这是怎么回事?我花了几个小时来解决这个问题.
我弄清楚我的问题是什么.保存文件后,我尝试重命名它,但是,我这样做的方式将此属性的关联作为文件.
错误:
$this->csv = $file_name;
Run Code Online (Sandbox Code Playgroud)
对:
$this->csv->name = $file_name;
Run Code Online (Sandbox Code Playgroud)
另外,我最初问这个问题是因为我无法让验证器工作,限制扩展.当我执行$ model-> validate()时,在客户端验证后它不会识别"xls"或"csv".我刚刚发现这是一个已知的问题,因为MIME TYPE验证器:https: //github.com/yiisoft/yii2/issues/6148
扩展问题的解决方案是将checkExtensionByMimeType设置为false:
[['csv'], 'file', 'skipOnEmpty' => false, 'extensions'=>['xls', 'csv'], 'checkExtensionByMimeType'=>false, 'maxSize'=>1024 * 1024 * 2],
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6864 次 |
| 最近记录: |