如何将文件上传到 yii basic 中上传文件夹中的服务器。我试过了,但它的 npt 有效

它没有将文件上传到项目中的文件夹。


如何上传文件?


public function actionCreate()

    {

        $model = new UploadForm();


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            $filename=$model->filename;

            $model->file= UploadedFile::getInstance($model,'file');

            $model->file->saveAs('uploads/' .$filename.'.'.$model->file->extension );


斯蒂芬大帝
浏览 121回答 3
3回答

慕尼黑5688855

它不上传,因为你调用$model->save()添加之前value到$model->file现场。代码应该看起来像if ($model->load(Yii::$app->request->post())) {    $filename = $model->ltkcnt_contracts_name;    $model->file = UploadedFile::getInstance($model, 'file');    if ($model->save()) {        $model->file->saveAs('uploads/' . $filename . '.' . $model->file->extension);    }}您应该阅读这篇文章以获取更多信息。

慕仙森

声明一个属性以在模型类中存储文件名。还要为此属性声明文件验证规则,以确保上传的文件具有特定的扩展名。然后,在控制器类中定义一个操作方法来收集用户提交的数据。    $model = new UploadForm();    if(isset(Yii::$app->request->post()))    {        $model->attributes=Yii::$app->request->post();        $model->file=UploadedFile::getInstance($model,'file');        if($model->save())        {            $model->file->saveAs('path/to/localFile');        }    }

海绵宝宝撒

<?phpnamespace app\models;use Yii;use yii\web\UploadedFile;class Contracts extends \yii\db\ActiveRecord{&nbsp; &nbsp; &nbsp;public $file;&nbsp; &nbsp; public static function tableName()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return 'uploads_table';&nbsp; &nbsp; }&nbsp; &nbsp; public function rules()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [['file'], 'file'],&nbsp; &nbsp; &nbsp; &nbsp; ];&nbsp; &nbsp; }&nbsp; &nbsp; public function attributeLabels()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'file' => 'Files',&nbsp; &nbsp; &nbsp; &nbsp; ];&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP