Yii2 multi-graph upload plug-in FileInput detailed tutorial, yii2fileinput
I have previously written an article about file upload, including the most basic yii2 file upload, asynchronous upload to upyun, and Baidu editor Image Upload, it seems that uploading multiple images is not perfect.
Today, we will introduce FileInput, a plug-in for uploading multiple images. As for why we have selected TA as the plug-in for uploading, this product has a leg up with yii2, using this plug-in not only makes it easy to add operations, but also deletes images silently in asynchronous mode during modification. The most important thing is that the interface effect integrates bootstrap, refreshing, concise, and beautiful, and looks comfortable.
Focus on the specific steps
First install components
Copy codeThe Code is as follows:
Composer require kartik-v/yii2-widget-fileinput "@ dev"
Make a necessary description: assume that we have a product table and a product image table, and the product image table only stores the product id and image address.
See basic usage
Use kartik \ file \ FileInput; // non-ActiveForm form echo '<label class = "control-label"> image </label>'; echo FileInput :: widget (['model' => $ model, 'attribute' => 'image [] ', 'options' => ['Multiple' => true]); // use ActiveForm echo $ form-> field ($ model, 'image [] ')-> widget (FileInput: classname (), ['options' => ['Multiple '=> true],]);
To upload multiple images, you only need to set multiple = true. Remember to select multiple images when selecting images.
As a result, you can select the image and submit the form directly. The file upload program needs to process it by yourself. If you have not implemented it yet, you can refer to the basic operations of file upload.
The only trouble with uploading multiple images is how convenient it is to modify it? Don't worry, FileInput has helped us solve it!
Let's take a look at the display of images during editing and how to asynchronously delete one or more images!
// View file use kartik \ file \ FileInput; <? Php $ form = ActiveForm: begin (['options' => ['enablesype '=> 'multipart/form-data'],]);?> <? Php echo $ form-> field ($ model, 'banner _ url [] ')-> label ('banner 图')-> widget (FileInput: classname (), ['options' => ['Multiple '=> true], 'ininoptions' => [// file format to be previewed 'previewfiletype' => 'image ', // preview the file 'initialpreview' => ['image 1', 'image 2', 'image 3'], // set the image to be displayed, the parameter 'initialpreviewconfig' => ['width' => '120px '] is equal to the width of the slice. // whether to display the preview image 'initialpreviewasdata' => true, // set 'uploadurl' => Url: toRoute (['/goods/ Sync-image']), // other parameters that need to be carried by asynchronous upload, such as the product id, 'uploadextradata' => ['goods _ id' => $ id,], 'uploadasync' => true, // the minimum number of uploaded files is limited to 'minfilecount' => 1. // The maximum number of uploaded files is limited to 'maxfilecount' => 10, // whether the "Remove" button is displayed, indicating the "Remove" button on the input. The "Remove" button on a non-specific image is "showRemove" => true ". // whether the" Upload "button is displayed, it refers to the upload button on the input, not the upload button on a specific image 'showupload' => true, // whether to display the [select] button, which refers to the [select] button on the input, the upload button 'showbrowse' => true for a non-specific image, // whether to select multiple files 'browseonzoneclick' => true To set the remove, upload, and display buttons for a specific image, you must set this option 'fileactionsettings' => [// set the viewing attribute of a specific image to false, the default value is true 'showzo' => false. // set the upload attribute of a specific image to true. The default value is true 'showupload' => true, // set the image removal attribute to true. The default value is true 'showdelete' => true,],], // some event behaviors 'ininevents' => [// callback method after the upload is successful. You need to view the data before performing the specific operation, generally, you do not need to set "fileuploaded" => "function (event, data, id, index) {console. log (data) ;}",],]);?> <? Php ActiveForm: end ();?>
As mentioned above, it is basically the basic attributes and settings of the component FileInput. Here we only list some common attributes. If necessary, you can view the detailed description of the attributes in the document.
As configured above, let's preview
It seems that the effect is very good. before writing php code implementation, we first implement the configuration of initialPreview and initialPreviewConfig In the controller.
Assume that the preceding view file is the details page for the user to display the product image. The current controller is the controller that renders the view file. You need to obtain the image associated with the product in the controller, used to display or delete or add a product image.
// Assume that the image of the product is $ relationBanners and $ id is the product id. // the data structure of $ relationBanners is as follows: /* Array * (* [0] => Array * (* [id] => 1484314 * [goods_id] => 1173376 * [banner_url] =>. /uploads/20160617/146612713857635322241 f2.png *) **) */$ relationBanners = Banner: find ()-> where (['goods _ id' => $ id]) -> asArray ()-> all (); // process the product banner diagram $ p1 = $ p2 = []; if ($ relationBanners) {foreach ($ relationBanners as $ k => $ v) {$ p1 [$ k] = $ v ['banner _ url']; $ p2 [$ k] = ['url' => url: toRoute ('/banner/delete '), 'key' => $ v ['id'],] ;}$ model = new Banner; return $ this-> render ('banner ', ['model' => $ model, 'p1' => $ p1, 'p2' => $ p2, 'id' => $ id]);
You can see that p1 is a set of image addresses. It is used to assign values to initialPreview.
P2 is a set of URLs and keys. It is used to assign values to initialPreviewConfig.
The url is the request address for image removal.
The key is the id of each image.
In this case, the pluginOptions in the view file should be like this.
'pluginOptions' => [// other code'initialPreview' => $p1,'initialPreviewConfig' => $p2,// other code],
Note: Set initialPreviewAsData to true. Otherwise, the preview image will not be displayed after an image is created.
We configured uploadUrl in the configuration file at the beginning. This parameter is the image address for asynchronous upload.
Now, the upload interface should be bald. After selecting an image, the effect is shown in figure 2,
Note that the upload of each small image is the upload of the corresponding small image. The upload and removal of the input box (in the lower right corner) is for all image operations, and the upload of the input box (in the lower right corner, ten images are also uploaded. Here we only need to describe the multiimage upload operations.
We have prepared the Image Upload address and additional parameters (such as the item id) required for the upload. The additional parameter configuration item is uploadExtraData. For details, see the configuration in the preceding View File.
Next let's look at the implementation of the/goods/async-image asynchronous upload program.
Public function actionAsyncImage () {// item ID $ id = Yii ::$ app-> request-> post ('goods _ id '); $ p1 = $ p2 = []; if (empty ($ _ FILES ['banner '] ['name']) | empty ($ _ FILES ['banner '] ['name'] ['banner _ url']) |! $ Id) {echo '{}'; return;} for ($ I = 0; $ I <count ($ _ FILES ['banner '] ['name'] ['banner _ url']); $ I ++) {$ url = '/banner/delete'; $ imageUrl = ''; // The image address returned after the image is uploaded is called. // The image receiving operation is not allowed, this is because we will also delete the $ model = new Banner; $ model-> goods_id = $ id; $ model-> banner_url = $ imageUrl; $ key = 0; if ($ model-> save (false) {$ key = $ model-> id;} // $ pathinfo = pathinfo ($ imageUrl ); // $ caption = $ pathinfo ['basename']; // $ size = $ _ FILES ['banner '] ['SIZE'] ['banner _ url'] [$ I]; $ p1 [$ I] = $ imageUrl; $ p2 [$ I] = ['url' => $ url, 'key' => $ key];} echo json_encode (['initialpreview' => $ p1, 'initialpreviewconfig' => $ p2, 'append' => true,]); return ;}
At this point, the upload of single and multi-graph is complete.
To delete an image, you can upload two images first. You can upload a single file or multiple files.
After the upload is successful, you can refresh the current page. Because we have implemented image preview in the controller at the beginning, we should have displayed the two images we have uploaded.
According to our configuration, the current preview chart should be like this.
Let's look at the implementation of the image deletion program (/banner/delete ).
public function actionDelete (){if ($id = Yii::$app->request->post('key')) {$model = $this->findModel($id);$model->delete();}Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;return ['success' => true];}
Note that the key is the key specified when the initialPreviewConfig item is configured. You can refer to the key in the controller or the key of p2 after the asynchronous upload is successful.
At this point, we have provided specific implementation of the components used for multi-graph upload and program code in yii2.
The above section describes all the detailed usage tutorials of the Yii2 component multimap upload plug-in FileInput. I hope this will be helpful to you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!