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配置參數(shù)'; 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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

YiiassetbundlesorganizeandmanagewebassetslikeCSS,JavaScript,andimagesinaYiiapplication.1.Theysimplifydependencymanagement,ensuringcorrectloadorder.2.Theypreventduplicateassetinclusion.3.Theyenableenvironment-specifichandlingsuchasminification.4.Theyp

In the MVC framework, the mechanism for the controller to render views is based on the naming convention and allows explicit overwriting. If redirection is not explicitly indicated, the controller will automatically find a view file with the same name as the action for rendering. 1. Make sure that the view file exists and is named correctly. For example, the view path corresponding to the action show of the controller PostsController should be views/posts/show.html.erb or Views/Posts/Show.cshtml; 2. Use explicit rendering to specify different templates, such as render'custom_template' in Rails and view('posts.custom_template') in Laravel

When saving data to the database in the Yii framework, it is mainly implemented through the ActiveRecord model. 1. Creating a new record requires instantiation of the model, loading the data and verifying it before saving; 2. Updating the record requires querying the existing data before assignment; 3. When using the load() method for batch assignment, security attributes must be marked in rules(); 4. When saving associated data, transactions should be used to ensure consistency. The specific steps include: instantiating the model and filling the data with load(), calling validate() verification, and finally performing save() persistence; when updating, first obtaining records and then assigning values; when sensitive fields are involved, massassignment should be restricted; when saving the associated model, beginTran should be combined

TocreateabasicrouteinYii,firstsetupacontrollerbyplacingitinthecontrollersdirectorywithpropernamingandclassdefinitionextendingyii\web\Controller.1)Createanactionwithinthecontrollerbydefiningapublicmethodstartingwith"action".2)ConfigureURLstr

The method of creating custom operations in Yii is to define a common method starting with an action in the controller, optionally accept parameters; then process data, render views, or return JSON as needed; and finally ensure security through access control. The specific steps include: 1. Create a method prefixed with action; 2. Set the method to public; 3. Can receive URL parameters; 4. Process data such as querying the model, processing POST requests, redirecting, etc.; 5. Use AccessControl or manually checking permissions to restrict access. For example, actionProfile($id) can be accessed via /site/profile?id=123 and renders the user profile page. The best practice is

AYiidevelopercraftswebapplicationsusingtheYiiframework,requiringskillsinPHP,Yii-specificknowledge,andwebdevelopmentlifecyclemanagement.Keyresponsibilitiesinclude:1)Writingefficientcodetooptimizeperformance,2)Prioritizingsecuritytoprotectapplications,

AYiideveloper'skeyresponsibilitiesincludedesigningandimplementingfeatures,ensuringapplicationsecurity,andoptimizingperformance.QualificationsneededareastronggraspofPHP,experiencewithfront-endtechnologies,databasemanagementskills,andproblem-solvingabi

TouseActiveRecordinYiieffectively,youcreateamodelclassforeachtableandinteractwiththedatabaseusingobject-orientedmethods.First,defineamodelclassextendingyii\db\ActiveRecordandspecifythecorrespondingtablenameviatableName().Youcangeneratemodelsautomatic
