【问题标题】:Save Multiple Image Files Using Kartik FileInput Widget使用 Kartik FileInput 小部件保存多个图像文件
【发布时间】:2015-09-18 06:38:53
【问题描述】:

我目前在我的系统中使用 Yii2 PHP 框架和 Kartik FileInput 小部件。我在多个文件上使用了跟随this guide 的输入文件上传,但它在我的系统中不起作用。我目前使用 MongoDB 作为我的数据库。这是我到目前为止的进展(原始,仅单次上传):

控制器actionCreate

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

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

    if($model->attachment) {
        $path = 'archive/contact/' . $model->attachment->baseName . '.' . $model->attachment->extension;
        $count = 0;
        {
            while(file_exists($path)) {
               $path = 'archive/contact/' . $model->attachment->baseName . '_'.$count.'.' . $model->attachment->extension;
               $count++;
            }
        }
        $model->attachment->saveAs($path);
        $model->attachment =  $path;
    }

    $model->save();

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

查看

echo FileInput::widget([
    'model' => $model,
    'attribute' => 'attachment[]',
    'name' => 'attachment[]',
    'options' => [
        'multiple' => true,
        'accept' => 'image/*'
    ],
    'pluginOptions' => [
        'showCaption' => false,
        'showRemove' => false,
        'showUpload' => false,
        'browseClass' => 'btn btn-primary btn-block',
        'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
        'browseLabel' =>  'Attach Business Card',
        'allowedFileExtensions' => ['jpg','gif','png'],
        'overwriteInitial' => false
    ],
]);

我还将包括我的模型

class Contact extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function collectionName()
    {
        return ['iaoy', 'contact'];
    }

    /**
     * @inheritdoc
     */
    public function attributes()
    {
        return [
            '_id', 'fname','lname','email','phone','address','contact_type','business_name','notes','company_id','date_added','attachment','sort'
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['_id', 'fname','lname','email','phone','address','contact_type','business_name','notes','company_id','date_added','attachment','sort'], 'safe'],
            [['fname','lname','contact_type','business_name'], 'required'],
            [['attachment'], 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 500*500],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            //'contact_id' => 'Contact ID',
            '_id' => 'Contact ID',
            'contact_type' => 'Contact Type',
            'business_name' => 'Business Name',
            'fname' => 'First Name',
            'lname' => 'Last Name',
            'email' => 'Email',
            'phone' => 'Phone',
            'address' => 'Address',
            'notes' => 'Notes',
            'attachment' => 'Attachment',
            'company_id' => 'Company ID',
        ];
    }
}

如何实现已经实现的多文件上传?任何想法都受到高度赞赏。

编辑:

到目前为止,这是我的多文件上传代码。我没有将它与我当前的代码(单个文件上传)混合,而是制作了一个新的 MVC。这基本上就是我在上面提到的指南中找到的内容,只做了很少的修改:

型号

<?php

namespace app\models;

use yii\base\Model;
use yii\web\UploadedFile;

class Upload extends Model
{
    public $file;

    public function attributes()
    {
        return [
            'file', 'urls'
        ];
    }

    public function rules()
    {
        return [
            [['file', 'urls'], 'safe'],
            [['file'], 'file','extensions' => 'png, jpg'],
            [['urls'],'string'],
        ];
    }
}

查看

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\file\FileInput;

    $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]);
?>

    <?php
        echo FileInput::widget([
            'model' => $model,
            'attribute' => 'file[]',
            'name' => 'file[]',
            'options' => [
                'multiple' => true,
                'accept' => 'image/*'
            ],
            'pluginOptions' => [
                'showCaption' => false,
                'showRemove' => false,
                'showUpload' => false,
                'browseClass' => 'btn btn-primary btn-block',
                'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
                'browseLabel' =>  'Attach Business Card',
                'allowedFileExtensions' => ['jpg','gif','png'],
                'overwriteInitial' => false
            ],
        ]);
    ?>
     <button>Submit</button>

<?php ActiveForm::end(); ?>

控制器

public function actionUpload()
{
    $model = new Upload();

    if ($model->load(Yii::$app->request->post())) {
        $model->file = UploadedFile::getInstances($model, 'file');

        foreach ($model->file as $key => $file) {
            $file->saveAs('archive/reimbursement/'. $file->baseName . '.' . $file->extension);//Upload files to server
            $model->urls .= 'archive/reimbursement/' . $file->baseName . '.' . $file->extension.'**';//Save file names in database- '**' is for separating images
        }
        $model->save();
        return $this->redirect(['viewuploads', 'id' => $model->id]);
    } else {
        return $this->render('upload', [
            'model' => $model,
        ]);
    }
}

我还在我的Contact.php模型rules函数中添加了'urls'

【问题讨论】:

  • 您在多文件上传过程中遇到了什么错误?
  • 我没有收到任何错误。只是它没有保存在我的数据库中。
  • 检查调试器中的错误或其他人放置您的多文件-上传代码。
  • 完成编辑。希望你能帮助我。
  • 好像你没有保存模型。试试if ($model-&gt;upload()) {$model-&gt;save(); }

标签: php mongodb file-upload yii2 multiple-file-upload


【解决方案1】:

试试这个:

控制器: 您应该将图像名称保存在数据库中('$model->urls')

public function actionUpload()
{
        $model = new Upload();

        if ($model->load(Yii::$app->request->post())) {
            $model->file = UploadedFile::getInstances($model, 'file');
            foreach ($model->file as $key => $file) {

                $file->saveAs('/uploads/'. $file->baseName . '.' . $file->extension);//Upload files to server
                $model->urls .= 'uploads/' . $file->baseName . '.' . $file->extension.'**';//Save file names in database- '**' is for separating images
            }
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('upload', [
                'model' => $model,
            ]);
        }
}

查看

<?= $form->field($model, 'file[]')->widget(FileInput::classname(), [
'options' => ['multiple' => 'true'],
]) ?>

型号

class Upload extends Model
{
public $file;
public function rules()
{
    return [
        [['file'], 'file','maxFiles' => 6],
        [['urls'],'string'],

    ];
}

另一个显示图像的视图

<?php
$images=explode('**',trim($model->urls));
foreach($images as $image)
{
     echo Html::img(Url::to('@web/' . $image, true));
}
?>

【讨论】:

  • 谢谢。但是,有一个错误:Getting unknown property: app\models\Upload::urls
  • 您应该在数据库和上传模型中定义“urls”列
  • 两者都做过。也许我做错了?我使用 MongoDB 作为我的数据库。
  • 没有收到此错误消息Invalid argument supplied for foreach()
  • @kaynewilder:你解决了吗?你能解决这个问题吗?
【解决方案2】:

我听说上传多张带有表单数据的图像的问题已经有一段时间了。 这是我的解决方案希望它可以帮助任何人

控制器

public function actionCreate()
{
    $createRoom = new Room();

    if ($createRoom->load(Yii::$app->request->post())) {
        $createRoom->roomFiles = UploadedFile::getInstances($createRoom, 'roomFiles');

        foreach ($createRoom->roomFiles as $key => $file) {
            $file->saveAs('uploads/'. $file->baseName . '.' . $file->extension);//Upload files to server
            $createRoom->room_images .= 'uploads/' . $file->baseName . '.' . $file->extension.'**';//Save file names in database- '**' is for separating images
        }
        $createRoom->save(false);
        return $this->redirect(['view', 'id' => $createRoom->room_id]);
    } else {
        return $this->render('create', [
            'createRoom' => $createRoom,
        ]);
    }
}

创建视图

<?= $form->field($createRoom, 'roomFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>

    <div class="form-group">
        <?= Html::submitButton($createRoom->isNewRecord ? 'Post' : 'Update', ['class' => $createRoom->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

房间模型

public function rules()
    {
       return [

 [['roomFiles'],  'file', 'skipOnEmpty' => false, 'extensions' =>     'png, jpg','maxFiles' => 4],

        ];
    }

【讨论】:

    【解决方案3】:

    在我的情况下,我必须以不同的方式设置另存为路径

    $uploadDir =  Yii::getAlias('@webroot/') . Yii::getAlias('@web/uploads');
    foreach ($model->file as $key => $file) {
        $file->saveAs($uploadDir . '/'. $file->baseName . '.' . $file->extension);//Upload files to server
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 2018-12-21
      • 2017-01-13
      相关资源
      最近更新 更多