如何使用Ajax在Kartik输入文件中发送所选文件? [英] How to use send the chosen file in Kartik Input File using Ajax?

查看:96
本文介绍了如何使用Ajax在Kartik输入文件中发送所选文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用drag&在我的Yii2应用程序中使用Kartik输入文件删除上传文件。
他们说这种拖放输入文件模型需要 AJAX 来发送数据。
我只是关注来自此处的Kartik输入文件的主要代码,以及来自此处的AJAX。我是编程新手,我还不知道如何使用AJAX。

I want to use drag & drop upload file using Kartik Input File in my Yii2 application. They said this "drag & drop" input file model need AJAX for send the data. I just following the main code for Kartik Input File from here, and the AJAX from here. I'm new in programming, and I dont know yet how to use AJAX.

所以我尝试在我的 view.php (path = app / views / students / view)中组合这样的代码。 php):

So I've tried to combine both of code like this in my view.php(path = app/views/students/view.php):

<script>
$(".btn-success").fileinput({
    uploadUrl: 'students/create',  // server upload action
    uploadAsync: true,
    maxFileCount: 1
});
</script>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?php echo '<label class="control-label">Choose an Excel file(.xlsx, .xls)</label>'; ?>
<?php
echo FileInput::widget([
    'model' => $model,
    'name' => 'attachment_48[]',
    'options' => [
        'accept' => 'doc/*', 'file/*',
        'enableLabel' => TRUE,
    ],
    'pluginOptions' => [
        'allowedFileExtensions' => ['xls', 'xlsx'],
        'showUpload' => TRUE,
        'showPreview' => TRUE,
        'maxFileSize' => 1024, //limit for choosen file
        'browseLabel' => 'Browse (Max 1MB)',
        'uploadUrl' => Url::to(['students/create']), // server upload action
        'maxFileCount' => 1
    ]
]);
?>

<?php echo '<br>' ?>
<?= Html::submitButton('<i class="glyphicon glyphicon-save-file"></i> UPLOAD FILE', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'], ['students/create']) ?>
<?php ActiveForm::end(); ?>

输入文件在视图中成功显示,但是当我点击提交按钮时,它不会发送我选择的文件。
我想处理我的 studentsController 中的数据(路径= app / controllers / studentsController。

The input file successfully showed in view, but when I clicked submit button, it doesn't send the file that I've choose. I want to process the data in my studentsController(path = app/controllers/studentsController.

我不知道怎么做将上面的行代码设置为我标记为'服务器上传操作'。

I'm not sure how to set the line code above that I've marked as 'server upload action'.

也许任何人都可以告诉我代码行是否错误,并且

Maybe anyone can tell me if my line of codes is wrong, and

Anyhelp将不胜感激。

Anyhelp will be appreciated.

谢谢。

推荐答案

使用Kartik FileInput小部件保存多个图像文件

Save Multiple Image Files Using Kartik FileInput Widget

Yii2 Kartik FileInput上传之前的多个图像温度和上传的图像显示和删除并更新新图像。

Yii2 Kartik FileInput Multiple Images Before Upload Temp and Uploaded Images Display and Delete and Update new images.

我想使用可下载的拖动我在Yii2应用程序中使用Kartik输入文件删除文件。他们说这个输入拖放文件模型需要AJAX发送数据。我只是从这里跟随Kartik输入文件的主代码和从这里跟随AJAX。我是新到专业编程,我仍然不知道如何使用AJAX。

I want to use a downloadable drag and drop file using the Kartik Input File in my Yii2 application. They said that this input drag & drop file model requires AJAX to send data. I just follow the main code for the Kartik input file from here and AJAX from here . I am new to programming, and I still do not know how to use AJAX.

因此,我尝试在我的Form.php(path = app /)中组合这两个代码modules / products / views / Form.php):

Therefore, I tried to combine both codes, like this, in my Form.php (path = app /modules/products/views/Form.php):

Table : products_images
id (Primary)
product_id  (FK)
image

Table : product
id (Primary)
Name
ect

此处查看表格...

<?php
use yii\helpers\Html;
use yii\helpers\Url;
use kartik\widgets\FileInput;
?>

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

<?php echo '<label class="control-label">Choose an Image file(.png, .jpg)</label>'; ?>

<?php
//For Update Form : Fetch Uploaded Images and create Array to preview
$imagesList = array();
$imagesListId = array();
foreach ($model->productsImages as $img) {
    $imagesList[] = Url::base(TRUE) . '/' . $img->image;
    $imagesListId[]['key'] = $img->id;
}
?>

<?php
    $empty_image = Url::base(TRUE) . "/uploads/image-upload-empty.png";

    echo FileInput::widget([
        'model' => $model,
        'attribute' => 'products_image[]',
        'name' => 'products_image[]',
        'options' => ['multiple' => true, 'accept' => 'image/*', 'id' => 'products_image_id'],
        'pluginOptions' => [
            'initialPreview' => $imagesList,
            'initialPreviewConfig' => $imagesListId,
            'deleteUrl' => Url::to(['products/delete-image']),
            'showCaption' => false,
            'showRemove' => false,
            'showUpload' => false,
            'browseClass' => 'btn btn-primary col-lg-6 col-md-8 col-sm-8 col-xs-6',
            'browseIcon' => '<i class="glyphicon glyphicon-plus-sign"></i> ',
            'browseLabel' => 'Upload Image',
            'allowedFileExtensions' => ['jpg', 'png'],
            'previewFileType' => ['jpg', 'png'],
            'initialPreviewAsData' => true,
            'overwriteInitial' => false,
            "uploadUrl" => Url::to(['products/upload']),
            'uploadExtraData' => ['products_id' => $model->id, 'is_post' => $model->isNewRecord ? 'new' : 'update'],
            'msgUploadBegin' => Yii::t('app', 'Please wait, system is uploading the files'),
            //'msgUploadThreshold' => Yii::t('app', 'Please wait, system is uploading the files'),
            //'msgUploadEnd' => Yii::t('app', 'Done'),
            'msgFilesTooMany' => 'Maximum 15 products Images are allowed to be uploaded.',
            'dropZoneClickTitle' => '',
            "uploadAsync" => true,
            "browseOnZoneClick" => true,
            "dropZoneTitle" => '<img src=' . $empty_image . ' />',
            'fileActionSettings' => [
                'showZoom' => true,
                'showRemove' => true,
                'showUpload' => false,
            ],
            'validateInitialCount' => true,
            'maxFileCount' => 15,
            'maxFileSize' => 5120, //5mb
            'msgPlaceholder' => 'Select attachments',
        ],
        'pluginEvents' => [
            'filebatchselected' => 'function(event, files) {
              $(this).fileinput("upload");

              }',
            /* 'uploadExtraData' => 'function() {
              var out = {}, key, i = 0;
              $(".kv-input:visible").each(function() {
              $el = $(this);
              key = $el.hasClass("kv-new") ? "new_" + i : "init_" + i;
              out[key] = $el.val();
              i++;
              });

              return out;
              }', */
            'filepredelete' => 'function(event, files) {
                //var abort = true;
                var index = uploaded_images.indexOf(files);
                if (index !== -1) uploaded_images.splice(index, 1);
                 console.log(uploaded_images);
                 $("#productsmaster-images_array").val(uploaded_images);
               //return abort;   
            }',
            'fileuploaded' => 'function(event, data, previewId, index){
               //alert( data.response.initialPreviewConfig[0].key);
          uploaded_images.push(data.response.initialPreviewConfig[0].key);
            console.log(uploaded_images);
            $("#productsmaster-images_array").val(uploaded_images);
          }',
        /* 'filepreupload' => 'function(event, data, previewId, index){
          var form = data.form, files = data.files, extra = data.extra,
          response = data.response, reader = data.reader;
          console.log(data.jqXHR);
          console.log("File pre upload triggered");
          }', */
        ],
    ]);
    ?>

<?= $form->field($model, 'images_array')->hiddenInput()->label(false) ?>

<?php echo '<br>' ?>
<?= Html::submitButton('<i class="glyphicon glyphicon-save-file"></i> UPLOAD FILE', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'], ['students/create']) ?>
<?php ActiveForm::end(); ?>

<?php
$script = <<< JS
   // initialize array    
   var uploaded_images = [];  
JS;
$this->registerJs($script);
?>

此处控制器文件:

<?php

/*
     * Post products Images Upload Action Via FileInput Yii2 Extention.
     */

    public function actionUpload() {
        $files = array();
        $allwoedFiles = ['jpg', 'png'];
        if ($_POST['is_post'] == 'update') {
            $products_id = $_POST['products_id'];
            if ($_FILES) {
                $tmpname = $_FILES['ProductsMaster']['tmp_name']['products_image'][0];
                $fname = $_FILES['ProductsMaster']['name']['products_image'][0];
                //Get the temp file path
                $tmpFilePath = $tmpname;
                //Make sure we have a filepath
                if ($tmpFilePath != "") {
                    //save the filename
                    $shortname = $fname;
                    $size = $_FILES['ProductsMaster']['size']['products_image'][0];
                    $ext = substr(strrchr($shortname, '.'), 1);
                    if (in_array($ext, $allwoedFiles)) {
                        //save the url and the file
                        $newFileName = Yii::$app->security->generateRandomString(40) . "." . $ext;
                        //Upload the file into the temp dir
                        if (move_uploaded_file($tmpFilePath, 'uploads/products/' . $newFileName)) {
                            $productsImages = new productsImages();
                            $productsImages->products_id = $products_id;
                            $productsImages->image_for = 'products';
                            $productsImages->image = 'uploads/products/' . $newFileName;
                            $productsImages->created_at = time();
                            $productsImages->save();
                            $files['initialPreview'] = Url::base(TRUE) . '/uploads/products/' . $newFileName;
                            $files['initialPreviewAsData'] = true;
                            $files['initialPreviewConfig'][]['key'] = $productsImages->id;
                            return json_encode($files);
                        }
                    }
                }
            } /* else {
              return json_encode(['error' => 'No files found for pload.']);
              } */
            return json_encode($files);
        } else {
            if (isset($_POST)) {
                if ($_FILES) {
                    $files = ProductsMaster::SaveTempAttachments($_FILES);
                    return json_encode($files);
                    $result = ['files' => $files];
                    Yii::$app->response->format = trim(Response::FORMAT_JSON);
                    return $result;
                } /* else {
                  echo json_encode(['error' => 'No files found for pload.']);
                  } */
            }
        }
    }


    /**
     * Uploaded Images Delete Action on Update Forms Action
     * @return boolean
     */
    public function actionDeleteImage() {
        $key = $_POST['key'];
        if (is_numeric($key)) {
            $products_image = ProductsImages::find()->where(['id' => $key])->one();
            unlink(Yii::getAlias('@webroot') . '/' . $products_image->image);
            $products_image->delete();
            return true;
        } else {
            unlink(Yii::getAlias('@webroot') . '/uploads/products/temp/' . $key);
            return true;
        }
    }

    /**
    ** Create Products
    **/
     public function actionCreate() {

          //Products Images
        // temp store image moved and save to database.. with generated forms.. 
            if (count($model->images_array) > 0) {
                $images_array = explode(',', $model->images_array);
                if (!empty($images_array) && $model->images_array != '') {
                    foreach ($images_array as $image) {
                        $file = Yii::$app->basePath . '/uploads/products/temp/' . $image;
                        $rename_file = Yii::$app->basePath . '/uploads/products/' . $image;
                        rename($file, $rename_file);
                        $productsImages = new productsImages();
                        $productsImages->products_id = $model->id;
                        $productsImages->image_for = 'products';
                        $productsImages->image = 'uploads/products/' . $image;
                        $productsImages->created_at = time();
                        $productsImages->save();
                    }
                }
            }

     }


    ?>

这里是模特菲尔。
我在附件模型中添加了一个加载函数。

Here Model Fiel. I added a load function to the attachment model.

<?php 

/*
     * Save Temp Images 
     */

    public static function SaveTempAttachments($attachments) {
        $files = "";
        $allwoedFiles = ['jpg', 'png'];
        if ($_FILES) {
            $tmpname = $_FILES['ProductsMaster']['tmp_name']['products_image'];
            $fname = $_FILES['ProductsMaster']['name']['products_image'];

            if (!empty($attachments)) {
                if (count($fname) > 0) {
                    //Loop through each file
                    for ($i = 0; $i < count($fname); $i++) {
                        //Get the temp file path
                        $tmpFilePath = $tmpname[$i];
                        //Make sure we have a filepath
                        if ($tmpFilePath != "") {
                            //save the filename
                            $shortname = $fname[$i];
                            $size = $attachments['ProductsMaster']['size']['products_image'][$i];
                            $ext = substr(strrchr($shortname, '.'), 1);
                            if (in_array($ext, $allwoedFiles)) {
                                //save the url and the file
                                $newFileName = Yii::$app->security->generateRandomString(40) . "." . $ext;
                                //Upload the file into the temp dir
                                if (move_uploaded_file($tmpFilePath, 'uploads/products/temp/' . $newFileName)) {
                                    $files['initialPreview'] = Url::base(TRUE) . '/uploads/products/temp/' . $newFileName;
                                    $files['initialPreviewAsData'] = true;
                                    // $files['uploadExtraData'][]['is_post'] = 'new';
                                    $files['initialPreviewConfig'][]['key'] = $newFileName;
                                }
                            }
                        }
                    }
                }
            }
        }
        return $files;
    }

?>

这篇关于如何使用Ajax在Kartik输入文件中发送所选文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆