我正在尝试使用DropZone上传多个文件。但是在控制器中检索文件名时会出现问题。请帮我找出我弄错的地方。我在下面发布了我的代码。
DropZone的HTML代码:
<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>
SCRIPT文件:
<?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);
在Controller 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-&gt; imageFiles时,它返回Array为空。 我期待从Yii :: $ app-&gt; request-&gt; isAjax == ture提交,但在我的情况下它总是假的。问题是什么?
答案 0 :(得分:0)
也许此软件包可以为您提供帮助。 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;
}