yii2 Multi graph Upload Component Tutorial

  • 2021-10-11 17:44:21
  • OfStack

Recently, when using yii2 to develop a form page, there is a need for multi-graph uploading. I found some components in this area, which are basically Amway fileInput, so I tried to use this library to complete the multi-graph uploading function of the back-end form page. In the process of using, we found that there are still many small details to pay attention to, so we recorded the process of using 1.

yii2-widget-fileinput the github address of this library is here, the installation part is very routine, just follow the document.

Let's look at several general operations shown in official documents:


use kartik\widgets\FileInput
// or 'use kartikile\FileInput' if you have only installed yii2-widget-fileinput in isolation
//  Use ActiveForm  And  model Bound single picture example 
echo $form->field($model, 'avatar')->widget(FileInput::classname(), [
  'options' => ['accept' => 'image/*'],
]);
//  Multi-graph upload example 
echo '<label class="control-label">Add Attachments</label>';
echo FileInput::widget([
  'model' => $model,
  'attribute' => 'attachment_1[]',
  'options' => ['multiple' => true]
]);
//  Unbound model How to use the 
echo '<label class="control-label">Upload Document</label>';
echo FileInput::widget([
  'name' => 'attachment_3',
]);
//  Examples that cannot be clicked 
echo '<label class="control-label">Select Attachment</label>';
echo FileInput::widget([
  'name' => 'attachment_4',
  'disabled' => true
]);

And these are routine operations. Let's imagine 1. We want to complete the product addition of Taobao. There is a product list and several pictures with a 1-to-many relationship. At this time, we need to use the multi-picture uploading function. And we also want to upload pictures asynchronously, so we can configure our fileInput component like this


<?= $form->field($model, 'image[]')->label($label)->widget(FileInput::classname(), [
  // 'name' => 'ImgSelect',
  'language' => 'zh-CN', 
  'options' => ['multiple' => true, 'accept' => 'image/*'], 
  'pluginOptions' => [ 
    'initialPreview' => $initialPreview, 
    'initialPreviewConfig' => $initialPreviewConfig, 
    'allowedPreviewTypes' => ['image'], 
    'allowedFileExtensions' => ['jpg', 'gif', 'png'], 
    'previewFileType' => 'image', 
    'overwriteInitial' => false, 
    'browseLabel' => ' Select a picture ',
    'msgFilesTooMany' => " Select the number of pictures to upload ({n})  Maximum number of pictures allowed exceeded {m} ! ", 
    'maxFileCount' => 5,// Maximum number of pictures allowed to be uploaded 5 Zhang  
    'maxFileSize' => 2048,// Limit the picture to the maximum 200kB 
    'uploadUrl' => Url::to(['/upload/image']),
    //'uploadExtraData' => ['testid' => 'listimg'], 
    'uploadAsync' => true,// Configure asynchronous upload or synchronous upload  
  ],
  'pluginEvents' => [ 
    'filepredelete' => "function(event, key) { 
        return (!confirm(' Confirm that you want to delete ')); 
      }", 
    'fileuploaded' => 'function(event, data, previewId, index) { 
        $(event.currentTarget.closest("form")).append(data.response.imgfile);
      }', 
    'filedeleted' => 'function(event, key) { 
        $(event.currentTarget.closest("form")).find("#"+key).remove(); 
        return;
      }', 
  ]
]); ?>

We configure the configuration of picture browsing in the controller and pass it in. I have added configuration to the key points in the code. We can see that the asynchronous uploaded url has been configured to the upload/image controller, and we also added the callback of js when the operations such as deletion and upload are completed.

As mentioned above, we have listed one of the basic properties and settings of the component FileInput. If necessary, please refer to the documentation for a detailed description of the properties.

Look at the controller that uploads pictures, how do we write this function actionImage


/** 
  *  Upload pictures to temporary directory  
  * @return string 
  * @throws \yii\base\Exception 
  */ 
 public function actionImage() 
 { 
   if (Yii::$app->request->isPost) { 
     $res = []; 
     $initialPreview = []; 
     $initialPreviewConfig = []; 
     $images = UploadedFile::getInstancesByName("UploadImage[image]"); 
     if (count($images) > 0) { 
       foreach ($images as $key => $image) { 
         if ($image->size > 2048 * 1024) { 
           $res = ['error' => ' The maximum size of the picture cannot exceed 2M']; 
           return json_encode($res); 
         } 
         if (!in_array(strtolower($image->extension), array('gif', 'jpg', 'jpeg', 'png'))) { 
           $res = ['error' => ' Please upload standard picture file ,  Support gif,jpg,png And jpeg.']; 
           return json_encode($res); 
         } 
         $dir = '/uploads/temp/'; 
         // Generate only 1uuid The name of the picture to be saved to the server  
         $pickey = ToolExtend::genuuid(); 
         $filename = $pickey . '.' . $image->getExtension();
         // If the folder does not exist, create a new folder  
         if (!file_exists(Yii::getAlias('@backend') . '/web' . $dir)) { 
           FileHelper::createDirectory(Yii::getAlias('@backend') . '/web' . $dir, 777); 
         } 
         $filepath = realpath(Yii::getAlias('@backend') . '/web' . $dir) . '/'; 
         $file = $filepath . $filename; 
         if ($image->saveAs($file)) { 
           $imgpath = $dir . $filename; 
           /*Image::thumbnail($file, 100, 100) 
             ->save($file . '_100x100.jpg', ['quality' => 80]); 
*/ 
          //  array_push($initialPreview, "<img src='" . $imgpath . "' class='file-preview-image' alt='" . $filename . "' title='" . $filename . "'>"); 
           $config = [ 
             'caption' => $filename, 
             'width' => '120px', 
             'url' => '../upload/delete', // server delete action 
             'key' => $pickey,
             'extra' => ['filename' => $filename] 
           ];
           array_push($initialPreviewConfig, $config); 
           $res = [ 
             "initialPreview" => $initialPreview, 
             "initialPreviewConfig" => $initialPreviewConfig, 
             "imgfile" => "<input name='image[]' id='" . $pickey . "' type='hidden' value='" . $imgpath . "'/>",
             'filename' => $filename,
             'imagePath' => $imgpath,
           ]; 
         }
       } 
     } 
     return json_encode($res); 
   } 
 }

At this point, we have achieved the work of uploading multiple pictures perfectly.

In order to realize the deletion effect of pictures, you can upload two pictures first. You can upload it in a single sheet or in multiple sheets.

After uploading successfully, you can refresh the current page, because we have previewed the pictures in controller since 1, so we should show the two pictures we have uploaded.

As for the deletion function, I don't talk about it. As long as I configure the deleted url in browsing, it is also a kind of operation.

Summarize


Related articles: