如何使用 Dropzone 在 YII2 中上传多个文件?

How to upload multiple file in YII2 using Dropzone?

我正在尝试使用 DropZone 上传多个文件。但是在控制器中检索文件名时遇到问题。请帮我找出我犯错的地方。我在下面发布了我的代码。

HTML DropZone 代码:

<div class="dropzone dropzone-file-area" id="my-dropzone"></div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update',
                ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary',
                    'id' => 'imageSubmit']) ?>
        </div>

脚本文件:

    <?php
$htmlString = "http://localhost/project/backend/web/news/create";
$this->registerJs(
    "Dropzone.autoDiscover = false;
  $(document).ready(function() {
      var myDropzone = new Dropzone('#my-dropzone', {
          url: '$htmlString',
          autoProcessQueue: false,
          enqueueForUpload: false,
          autoDiscover: false,
          addRemoveLinks: true,
          uploadMultiple: true,
          paramName: 'News[imgFiles]',
          maxFiles: 10,
          maxFilesize: 2,
          parallelUploads: 10,
          acceptedFiles: 'image/*',
          params: {
              '_csrf-backend': $('input[name=_csrf-backend]').val()
          },
          success: function (file, response) {
            var imgName = response;
            file.previewElement.classList.add('dz-success');
            console.log('Successfully uploaded :' + imgName);

        },

           init: function () {

            var myDropzone = this;

           var submitButton = document.querySelector('#imageSubmit');

            submitButton.addEventListener('click', function (file) {

                if (myDropzone.getQueuedFiles().length > 0) {

                    var submitfiles = false;

                    if (submitfiles === true) {
                        submitfiles = false;
                        return;
                    }

                    file.preventDefault();
                    myDropzone.processQueue();

                    myDropzone.on('complete', function (data, xhr, formData) {
                        submitfiles = true;
                        $('#imageSubmit').trigger('click');
                    });

                }
            });
        }
      });

  });", $this::POS_END);

在控制器 actionCreate() 方法中:

 public function actionCreate()
{
    $model = new News();
    if (Yii::$app->request->isAjax) {
        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                Yii::$app->session->setFlash("success", "success");
                return true;
            } else {
                print_r($model);
                exit;
            }
        }
    }
    if ($model->load(Yii::$app->request->post()) ) {
        $model->imageFiles = UploadedFile::getInstances($model, 'imgFiles');
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

当我在拖放框中添加图片并单击提交按钮时,拖放框中的图片显示成功结果。但是当我尝试打印 $model->imageFiles 时,它的 return 数组为空。 我期待从 Yii::$app->request->isAjax == ture 提交,但在我的情况下它总是错误的。有什么问题?

也许这个包对你有帮助。 composer require --prefer-dist perminder-klair/yii2-dropzone "dev-master"。用于表单属性:

<?= $form->field($model, 'city_id')->widget(DropZone::className(), [
        'options'      => [
            'maxFilesize' => '2',
        ],
        'clientEvents' => [
            'complete'    => "function(file){console.log(file)}",
            'removedfile' => "function(file){alert(file.name + ' is removed')}",
        ],
    ]) ?>

并且它用于控制器操作:

public function actionUpload()
{
    $fileName = 'file';
    $uploadPath = './files';

    if (isset($_FILES[$fileName])) {
        $file = \yii\web\UploadedFile::getInstanceByName($fileName);

        //Print file data
        //print_r($file);

        if ($file->saveAs($uploadPath . '/' . $file->name)) {
            //Now save file data to database

            echo \yii\helpers\Json::encode($file);
        }
    }

    return false;
}