一个表格中的2个文件上传输入字段yii2

时间:2017-08-01 19:04:36

标签: php file-upload upload yii2

我有2列(pic,pic2)的表格,我的上传表单适用于第一个文件输入。图片的名称记录到“pic”列中,文件上传到服务器。如何将其扩展为上传2个文件?帮助请

模型

public $ upload_file;

    public function uploadFile() {
    // get the uploaded file instance

    $image = UploadedFile::getInstance($this, 'upload_file');

    // if no image was uploaded abort the upload
    if (empty($image)) {
        return false;
    }
    $dir = Yii::getAlias('@frontend' . '/web/' . Yii::$app->params['fileUploadUrl']).$this->pic; 
    if (file_exists($dir)) {
        unlink($dir);
    } 
    // generate random name for the file
    $this->pic = time(). '.' . $image->extension;
    // the uploaded image instance
    return $image;
}

public function getUploadedFile() {
    // return a default image placeholder if your source avatar is not found
    $pic = isset($this->pic) ? $this->pic : 'default.png';
    $dir = Yii::getAlias('@frontend' . '/web/' . Yii::$app->params['fileUploadUrl']);
    if (!is_dir($dir)) {
        FileHelper::createDirectory($dir);
    } else {
        return $dir . $pic;            
    }

}
控制器中的

操作

    public function actionCreate()
{
    $model = new Blog();

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

        $upload_file = $model->uploadFile();

        if ($model->validate()) {   
            if($model->save()) {

                if ($upload_file !== false) {
                    $path = $model->getUploadedFile();
                    $upload_file->saveAs($path);
                }

                return $this->redirect(['view', 'id' => $model->id]);
            }

        }
    }

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

}

查看

    <?= $form->field($model, 'upload_file')->widget(FileInput::classname(), [
    'options' => ['accept' => 'image/*'],
]); ?>
<?= $form->field($model, 'upload_file2')->widget(FileInput::classname(), [
    'options' => ['accept' => 'image/*'],
]); ?>

3 个答案:

答案 0 :(得分:0)

您可以为class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) @python_2_unicode_compatible class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text

编写相同的代码
'upload_file2'

或者您可以将一些小部件用于多个上传文件,例如that

答案 1 :(得分:0)

如果您不需要两个单独的输入进行上传 - 您可以执行以下操作 - 将“maxFiles”添加到模型的规则中。

public function rules() { return [ [['upload_file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 2], ]; }

并在uploadFile操作中更改:

$image = UploadedFile::getInstance($this, 'upload_file');

于: $image = UploadedFile::getInstances($this, 'upload_file');

最后在您的视图中更改

<?= $form->field($model, 'upload_file')->widget(FileInput::classname(), [ 'options' => ['accept' => 'image/*'], ]); ?>

到:

<?= $form->field($model, 'upload_file[]')->widget(FileInput::classname(), [ 'options' => ['accept' => 'image/*', 'multiple' => true] , ]); ?>

答案 2 :(得分:0)

以这种方式找到解决方案:)

控制器中的一切

    public function actionRegistration()
{
    $model = new Registration();
    $i = 0;

    $imageArray = ['upload_file1','upload_file2','upload_file3','upload_file4'];
    if ($model->load(Yii::$app->request->post())) {

        foreach ($imageArray as $imageUpload) {
            $i++;
            $field_name = 'pic'.$i;
            $image = UploadedFile::getInstance($model, $imageUpload);
            // if no image was uploaded abort the upload
            if (empty($image)) {
                return false;
            }

            // generate random name for the file
            $model->$field_name = 'pic'.$i.'_'. time(). '.' . $image->extension;

            if ($image !== false) {
                $pic = $model->$field_name ? $model->$field_name : 'default.png';
                $dir = Yii::getAlias('@frontend' . '/web/' . Yii::$app->params['fileUploadUrl']);
                if (!is_dir($dir)) {
                    FileHelper::createDirectory($dir);
                }

                $image->saveAs($dir.$pic);
            }

        }
        if (!$model->save()){
            var_dump($model->errors);
        } 
        return $this->refresh();
    }

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