Yii2 如何使用自定义文件名保存文件?

Yii2 How to save file with custom file name?

如何使用自定义文件名保存文件?我在我的网站上使用了 gii generator,现在我的表单中有一个文件输入,我想要的是在保存文件后,名称是从 report_id 中获取的,这是我的 primary key。例如,1_.docx 1 是我的 report_id。我还有一个 doc_name 字段,是的,我可以保存我的文件并在 doc_name 中获取名称。例如,sample.docx。但我的问题是当我使用 report_id 并且例如保存数据时,文件名仅为 .docx

这是我的控制器:

  public function actionCreate()
{
    $model = new reportDetails();
    if ($model->load(Yii::$app->request->post())) 
{      
    $project= $model->doc_name;
    $model->upload_file= UploadedFile::getInstance($model,'doc_file');
    $model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
    $model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
    $model->doc_name=$project.'.'.$model->upload_file->extension;
    $model->save();

    Yii::$app->getSession()->setFlash('success','Data saved!');
    return $this->redirect(['view','id'=> $model->report_id]);
    } 

    else {

    return $this ->render('create', [
        'model'=>$model,
    ]);
    }         

}

如您所见,$project=$model->doc_name; 这是我保存数据时的代码,文件名将从 doc_name 中获取,但如果我将其更改为 report_id,当我保存它时,结果为空白或仅 .docx

这是我的 _form:

  <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
     &nbsp;&nbsp;&nbsp;<?= Html::button('<i class="fa fa-plus"></i>&nbsp;Add Person', ['value' => Url::to('index.php?r=name/create'), 'class' => 'btn btn-custom-pos btn-success', 'id' => 'officialsfor']) ?>
        </br>  
        </br> 
  <?php Pjax::begin(['id' => 'for_from']) ?>
      <div class="col-sm-6">
     <?= $form->field($model, 'doc_for')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
            'name_id',
            function($model, $defaultValue){
              return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
             ],
            ]); ?>
      </div>
      <div class="col-sm-6">
    <?= $form->field($model, 'doc_from')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
           'name_id',
            function($model, $defaultValue){
            return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
            ],
            ]); ?>
 <?php Pjax::end(); ?>
      </div>
        </br>
        </br></br></br>
      <div class="broder" style=" border-radius: 5px; padding: 12px; ">    
      </div>
  <div class="col-sm-6">
      <?= $form->field($model, 'user_id')->textInput(['type' => 'hidden','style'=>'width:500px;','placeholder' => 'Enter a Reference No....','value' =>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name)]) ?>
       <?= Html::activeLabel($model, 'user_id', ['label'=>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name),'style' => 'font-size: 21px;','class' => 'color']) ?>
      <br>
      <br>
      <?= $form->field($model, 'reference_no')->textInput(['style'=>'width:500px','placeholder' => 'Enter a Reference No....']) ?>
      <?= $form->field($model, 'subject')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Subject....']) ?>
    <?= $form->field($model, 'doc_date')->widget(
        DatePicker::className(), [
            'inline' => false,
            'options' => ['placeholder' => 'Choose a Entry Date ...'],
            'clientOptions' => [
            'autoclose' => true,
            'format' => 'yyyy-mm-dd'
              ]
             ]);?>
  </div>
  <div class="col-sm-6" style="padding-top: 14px; ">
         </br>
         </br>
         </br></br>
    <?= $form->field($model, 'drawer_id')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Drawer ID....', ]) ?>
    <?= $form->field($model, 'doc_name')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Document Name....']) ?>
      <?= $form->field($model, 'doc_file')-> widget(
        FileInput::classname(),[
      'name' => 'doc_file',
      'options' => ['accept' => '.docx','.doc','.docs'],
      'pluginOptions' => [
          'showPreview' => false,
          'showCaption' => true,
          'showRemove' => true,
          'showUpload' => false
            ]
        ]);
      ?> 
  </div>
</div>
</br>
<div class="row">
  <div class="col-sm-12 text-center">
    <div class="form-group">
      <?= Html::submitButton($model->isNewRecord ? '<i class="fa fa-plus"></i>&nbsp;Create' : '<i class="fa fa-pencil"></i>&nbsp;Update', ['class' => $model->isNewRecord ? 'btn btn-success'  : 'btn btn-success','style' => 'padding:10px 60px;']) ?>
    </div>
  </div>
</div>
<?php ActiveForm::end(); ?>

正如你所说,report_id是主键,所以在将新记录保存到数据库之前你不会得到它。

按照您的逻辑,插入正在处理新记录。所以你需要像下面这样更新你的代码。检查一下。

public function actionCreate()
{
    $model = new reportDetails();
    if ($model->load(Yii::$app->request->post())) 
    {      
        $project= $model->doc_name;
        $model->upload_file = UploadedFile::getInstance($model,'doc_file');
        $model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
        $model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
        $model->doc_name=$project.'.'.$model->upload_file->extension;
        $model->save();

        // after save you will get report_id
        rename('uploads/'.$project.'.'.$model->upload_file->extension, 'uploads/'.$model->report_id.'.'.$model->upload_file->extension);
        $model->doc_file='uploads/'.$model->report_id.'.'.$model->upload_file->extension;
        $model->doc_name=$model->report_id.'.'.$model->upload_file->extension;
        $model->save();


        Yii::$app->getSession()->setFlash('success','Data saved!');
        return $this->redirect(['view','id'=> $model->report_id]);
    } 

    else {

        return $this ->render('create', [
            'model'=>$model,
        ]);
    }         

}