如何将文件上传到yii2中的目录?

时间:2014-05-11 11:40:02

标签: php yii2

我有一个ActiveForm,我想添加一个用户可以上传照片的字段。 问题是我没有在用户表和每个用户的图像属性 输入字段在' yii'期望模型和属性如下。

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

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

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

6 个答案:

答案 0 :(得分:45)

按照官方文档

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

如果您正在使用&#34;基本&#34;应用程序模板然后应在web下创建文件夹上传。

那就是它。加载页面并尝试上传。 Uplaods最终应该是基本/网络/上传。

答案 1 :(得分:14)

在您的视图中

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

答案 2 :(得分:6)

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

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

答案 3 :(得分:2)

我非常喜欢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;
    }

答案 4 :(得分:0)

在上传的代码

后提供此代码
  //save the path in DB..
                $model->file = 'uploads/'.$imageName.'.'.$model->file->extension;
                $model->save();

答案 5 :(得分: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 是型号名称。