Let’s take a look at the code first:
First look at the View part:
<form action="<?= Url::to(['default/datafile']) ?>" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="myFile" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form>
The above action is built using the YII helper class The url that can be recognized internally is actionDatafile()
in DeaufaultController.php (recommended tutorial: yii framework)
public function actionDatafile(){ if(empty($_FILES)){ $status = 1; $info = '没有文件上传'; } if($_FILES['myFile']['error'] === 0 || $_FILES['myFile']['error'] === '0' ){ //文件上传成功 $tmp = pathinfo($_FILES['myFile']['name']); $new_fname = $tmp['filename'].'_'.rand(1000000,9999999).'.'.$tmp['extension']; echo $new_fname; if(!move_uploaded_file($_FILES['myFile']['tmp_name'], '../runtime/file/'.$new_fname)){ $status = 1; $info = '上传(移动)失败'; }else{ $status = 0; $info = '上传成功'; } } else { //文件上传失败 $info = '文件上传失败'; switch($_FILES['myFile']['error']){ case 1: $info = '上传文件超过php.ini中upload_max_filesize配置参数'; break; case 2: $info = '上传文件超过表单MAX_FILE_SIZE选项指定的值'; break; case 3: $info = '文件只有部份被上传'; break; case 4: $info = '没有文件被上传'; break; case 5: $info = '上传文件大小为0'; break; } $status = 1; } return $info; }
found after execution
Solution:
1. Check the configuration (php.ini)
file_uploads, upload_max_filesize, post_max_size, and upload_tmp_dir have been set.
2. Check the parameters
Found crsf in the parameters. This parameter is included in the yii framework verification. When it comes to verification, it is similar to the error message. Add the cancellation verification code, as follows:
public function beforeAction($action) { if ($action->id == 'datafile') { $this->enableCsrfValidation = false; } return parent::beforeAction($action); }
For more programming-related content, please pay attention to the Programming Introduction column on the php Chinese website!
The above is the detailed content of yii2 failed to upload file. For more information, please follow other related articles on the PHP Chinese website!