3

私は何とか試してみましたが、最終的には機能しません: http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html

エラー メッセージは表示されず、データはデータベース (MongoDB) に保存されません。ここに私のコードスニペットがあります:

Contact.php モデル

class Contact extends ActiveRecord
{
    public $file;

    public $attachment;

    /**
     * @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', 'urls'
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['_id', 'fname','lname','email','phone','address','contact_type','business_name','notes','company_id','date_added','attachment','sort', 'urls'], 'safe'],
            [['fname','lname','contact_type','business_name'], 'required'],
            [['attachment'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 10, 'maxSize'=>20*1024*1024,],
            //[['urls'],'string'],
        ];
    }

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

    public function upload()
    {
        if ($this->validate()) { 
            foreach ($this->attachment as $file) {
                $file->saveAs('archive/contact/' . $file->baseName . '.' . $file->extension);
            }
            return true;
        } else {
            return false;
        }
    }
}

ContactController.php コントローラー

public function actionCreate()
{
    $session = Yii::$app->session;      
    $model = new Contact();

    if($model->load(Yii::$app->request->post())) {
    //if (Yii::$app->request->isPost) {
        $model->company_id = new \MongoId($session['company_id']);

        date_default_timezone_set('Asia/Manila');
        $model->date_added = date('d-m-Y', time());

        $model->attachment = UploadedFile::getInstance($model, 'attachment');
        /*if($model->attachment) {
            foreach ($model->attachment as $key => $file) {
                $file->saveAs('archive/contact/'. $file->baseName . '.' . $file->extension); //Upload files to server
                $model->urls .= 'archive/contact/' . $file->baseName . '.' . $file->extension.'**'; //Save file names in database- '**' is for separating images
            }

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

        if($model->save()) {
            Yii::$app->session->setFlash('success', "Successfully created contact!");
        } else {
            $model->save();                  
            if($model->save()) {
                Yii::$app->session->setFlash('success', "Successfully created contact!");
            } else {
                Yii::$app->session->setFlash('error', "Contact creation failed!");
            }
        }

        $model->refresh();
        return $this->redirect(['index', 'id' => $session['user_id']]);

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

_form.php ビュー

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

何が欠けているか、間違っているように見えるかわかりません。MongoDB や Kartik のウィジェットを使用しているからでしょうか? 以下にあなたの考えを教えてください。

4

3 に答える 3

0

あなたが投稿した記事から:

if (Yii::$app->request->isPost) {
    $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
    if ($model->upload()) {
        // file is uploaded successfully
        return;
    }
}

アップロード メソッドは最初のコード ブロックにあり、ファイル システムにファイルを保存します。

public function upload()
{
    if ($this->validate()) {
        $this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
        return true;
    } else {
        return false;
    }
}

バイナリとしてデータベースに保存する場合は、ファイルの内容 ( file_get_contentsなど) を読み取り、それをモデル属性に割り当てる必要があります。

于 2015-09-23T19:03:09.290 に答える