使用Kartik FileInput Widget保存多个图像文件 [英] Save Multiple Image Files Using Kartik FileInput Widget

查看:737
本文介绍了使用Kartik FileInput Widget保存多个图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在我的系统中使用Yii2 PHP框架和Kartik FileInput 小部件。我使用了遵循本指南的输入文件上传在多个文件,但它没有在我的系统中工作。我目前正在使用MongoDB作为我的数据库。这是我迄今的进度(原始,单一上传只):
$ b

控制器, actionCreate

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

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

if($ model-> attachment){
$ path ='archive / contact /'。 $ model-> attachment-> baseName。 ''。 $模型 - > attachment->扩展名;
$ count = 0;
{
while(file_exists($ path)){
$ path ='archive / contact /'。 $ model-> attachment-> baseName。 '_'。$ count。'。'。 $模型 - > attachment->扩展名;
$ count ++;


$ model-> attachment-> saveAs($ path);
$ model-> attachment = $ path;
}

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

查看

  echo FileInput :: widget([$ b $'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'=>'附上名片',
'allowedFileExtensions'=> ['jpg','gif','png'],
'overwriteInitial'=> false
],
]);

我也会加入我的模特

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

$ b / **
* @inheritdoc
* /
公共函数属性()
{
return [
'_id','fname','lname','email','phone','address','contact_type','business_name','notes','company_id','date_added','attachment' ,'sort'
];

$ b / **
* @inheritdoc
* /
公共函数规则()
{
return [
['_id','fname','lname','email','phone','address','contact_type','business_name','notes','company_id','date_added','附件','排序'],'安全'],
[[''fname','lname','contact_type','business_name'],'required'],
[ ],'file','extensions'=> ['png','jpg','gif'],'maxSize'=> 500 * 500],
];

$ b / **
* @inheritdoc
* /
public function attributeLabels()
{
return [
//'contact_id'=> '联系人ID',
'_id'=> '联系人ID',
'contact_type'=> 'Contact Type',
'business_name'=> 'Business Name',
'fname'=> '名字',
'lname'=> '姓',
'email'=> 'Email',
'phone'=> 'Phone',
'address'=> 'Address',
'notes'=> 'Notes',
'attachment'=> '附件',
'company_id'=> '公司ID',
];






$ b

如何实现多文件上传实施?任何想法,高度赞赏。

编辑:

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

模型

 <?php 

名称空间app \models;

使用yii\base\Model;
使用yii\web\UploadedFile;

类上传扩展模型
{
public $ file;

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

$ b $公共函数规则()
{
return [
[['file','urls'],'safe'],
[['file'],'file','extensions'=> 'png,jpg'],
[['urls'],'string'],
];


查看

 <?php 
使用yii \helpers\Html;
使用yii\widgets\ActiveForm;
使用kartik \file\FileInput;
$ b $ 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'=>'附上名片',
'allowedFileExtensions'=> ['jpg','gif','png'],
'overwriteInitial'=> false
],
]);
?>
<按钮>提交< /按钮>

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

控制器

< pre $ public function actionUpload()
{
$ model = new Upload();
$ b $ if($ model-> load(Yii :: $ app-> request-> post())){
$ model-> file = UploadedFile :: getInstances ($ model,'file');
$ b foreach($ model->文件为$ key => $ file){
$ file-> saveAs('archive / reimbursement /'。$ file-> baseName 。'。'。$ file-> extension); //将文件上传到服务器
$ model-> url。='archive / reimbursement /'。 $ file-> baseName。 ''。 '**'; //保存文件名在数据库中'**'用于分隔图像
}
$ model-> save();
return $ this-> redirect(['viewuploads','id'=> $ model-> id]);
} else {
return $ this-> render('upload',[
'model'=> $ model,
]);


$ / code $ / pre
$ b $我也加了'网址'在我的 Contact.php 模型规则函数

您应该将图像名称保存在数据库中('$ model-> url'')解决方案



$ p $ public function actionUpload()
{
$ model = new Upload();
$ b $ if($ model-> load(Yii :: $ app-> request-> post())){
$ model-> file = UploadedFile :: getInstances ($ model,'file');
foreach($ model->文件为$ key => $ file){

$ file-> saveAs('/ uploads /'。$ file-> baseName。 '。'。$ file-> extension); //将文件上传到服务器
$ model-> url =uploads /。 $ file-> baseName。 ''。 '**'; //保存文件名在数据库中'**'用于分隔图像
}
$ model-> save();
return $ this-> redirect(['view','id'=> $ model-> id]);
} else {
return $ this-> render('upload',[
'model'=> $ model,
]);


code

$ b $ p

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

模型

  class上传扩展模型
{
public $ file;
public function rules()
{
return [
[['file'],'file','maxFiles'=> 6],
[['urls'],'string'],

];

$ / code>

显示图片的另一个视图

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


I am currently using Yii2 PHP framework and Kartik FileInput widget in my system. I have used followed this guide of input file uploads on multiple files but it didn't work in my system. I am currently using MongoDB as my database. Here's my progress so far (original, single upload only):

Controller, 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,
    ]);
}   

View

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
    ],
]);

I'll also be including my Model

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',
        ];
    }
}

How do I implement the multiple file upload having this already implemented? Any thoughts are highly appreciated.

EDIT:

Here's my multi file upload code so far. I didn't mixed it with my current code (single file upload) instead I made a new MVC. It's just basically what I found in the guide I mentioned above with just very little modifications:

Model

<?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'],
        ];
    }
}

View

<?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(); ?>

Controller

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,
        ]);
    }
}

I also added 'urls' in my Contact.php model rules function

解决方案

Try this:

Controller: you should save image name in database('$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,
            ]);
        }
}

View

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

Model

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

    ];
}

Another view for showing images

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

这篇关于使用Kartik FileInput Widget保存多个图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆