24

我有一个 ActiveForm,我想添加一个用户可以上传照片的字段。问题是我在用户表中没有图像属性,并且“yii”中的每个输入字段都需要一个模型和一个属性,如下所示。

<?= $form->field($model, 'attribute')->input($platforms) ?>

我不想将图像分配给任何记录,也不想插入数据库,我希望将其上传到特定文件夹。

我还检查了 kartik 写的库,但也需要一个属性字段。

4

6 回答 6

48

按照官方文档

https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md

表格模型

namespace app\models;

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

/**
* UploadForm is the model behind the upload form.
*/
class UploadForm extends Model
{
/**
 * @var UploadedFile|Null file attribute
 */
public $file;

/**
 * @return array the validation rules.
 */
public function rules()
{
    return [
        [['file'], 'file'],
    ];
}
}
?>

表单视图

<?php
use yii\widgets\ActiveForm;

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

<?= $form->field($model, 'file')->fileInput() ?>

<button>Submit</button>

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

控制器

现在创建将表单和模型连接在一起的控制器:

<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;

class SiteController extends Controller
{
public function actionUpload()
{
    $model = new UploadForm();

    if (Yii::$app->request->isPost) {
        $model->file = UploadedFile::getInstance($model, 'file');

        if ($model->validate()) {                
            $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
        }
    }

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

而不是model->load(...)我们使用UploadedFile::getInstance(...). [[\yii\web\UploadedFile|UploadedFile]]不运行模型验证。它仅提供有关上传文件的信息。因此,您需要通过$model->validate(). 这会触发[[yii\validators\FileValidator|FileValidator]]需要文件的 :

 $file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE //in code framework

如果验证成功,那么我们将保存文件:

 $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);

如果您使用“基本”应用程序模板,则应在 web.xml 下创建文件夹上传。

而已。加载页面并尝试上传。上传应该以基本/网络/上传结束。

于 2014-07-16T20:43:18.280 回答
15

在你看来

use kartik\widgets\ActiveForm;
use kartik\widgets\FileInput;

$form = ActiveForm::begin(['options' => ['enctype'=>'multipart/form-data']]); //important
echo FileInput::widget([
                    'name' => 'filename',
                    'showUpload' => false,
                    'buttonOptions' => ['label' => false],
                    'removeOptions' => ['label' => false],
                    'groupOptions' => ['class' => 'input-group-lg']
                ]);
echo Html::submitButton('Submit', ['class'=>'btn btn-primary']);
ActiveForm::end();

在你的控制器中

$file = \yii\web\UploadedFile::getInstanceByName('filename');
$file->saveAs('/your/directory/'.$file->name);
于 2014-06-16T14:29:22.290 回答
6

为您的模型创建一个只读属性,public $image然后继续

 <?= $form->field($model, 'image')->fileInput() ?>
于 2014-05-12T04:03:26.890 回答
3

我真的很喜欢Yii2 Dropzone

安装:

composer require --prefer-dist perminder-klair/yii2-dropzone "dev-master"

用法:

<?php 
    echo \kato\DropZone::widget([
       'options' => [
           'url'=> Url::to(['resource-manager/upload']),
           'paramName'=>'image',
           'maxFilesize' => '10',
       ],
       'clientEvents' => [
           'complete' => "function(file){console.log(file)}",
           'removedfile' => "function(file){alert(file.name + ' is removed')}"
       ],
   ]);

   ?>

控制器:

public function actionUpload(){

        $model = new ResourceManager();
        $uploadPath = Yii::getAlias('@root') .'/uploads/';

        if (isset($_FILES['image'])) {
            $file = \yii\web\UploadedFile::getInstanceByName('image');
          $original_name = $file->baseName;  
          $newFileName = \Yii::$app->security
                            ->generateRandomString().'.'.$file->extension;
           // you can write save code here before uploading.
            if ($file->saveAs($uploadPath . '/' . $newFileName)) {
                $model->image = $newFileName;
                $model->original_name = $original_name;
                if($model->save(false)){
                    echo \yii\helpers\Json::encode($file);
                }
                else{
                    echo \yii\helpers\Json::encode($model->getErrors());
                }

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

        return false;
    }
于 2016-09-01T18:18:43.077 回答
0

在您上传代码后提供此代码

  //save the path in DB..
                $model->file = 'uploads/'.$imageName.'.'.$model->file->extension;
                $model->save();
于 2015-06-25T09:09:14.237 回答
0

如果您在上传时有多个文件,则必须为此使用 foreach。并且您应该在表中的列中使用文件的实际名称,并且必须存储该名称的加密值以避免在目录中重复..像这样的东西..

$userdocs->document_name = UploadedFile::getInstances($userdocs, 'document_name');

foreach ($userdocs->document_name as $key => $file) {
  $img_name = Yii::$app->security->generateRandomString();
  $file->saveAs('user/business_files/' . $img_name . '.' . $file->extension);
  $images = $img_name . '.' . $file->extension;
  $userdocs->actual_name = $file->name;
  $userdocs->user_id = $user->id;
  $userdocs->document_name = $images;
  $userdocs->save(false);
  $userdocs = new UserDocs();
}

这里会生成一个随机字符串,并将其与文档名称一起分配,并将其存储在表中。UserDocs模型名称。

于 2016-08-01T06:16:21.663 回答