The Bootstrap file upload plug-in File Input is a good file upload control, but there are not many cases in search and use. When using it, you also cross the river by touching the stone step by step. This control is presented on the interface, and the Uploadify I have used before is more beautiful and has more powerful functions. This article is mainly based on my own framework code case, introducing the use of File Input, the file upload plug-in.
1. Introduction to File Input for File Upload Plugin
The homepage address of this plug-in is: http://plugins.krajee.com/file-input. You can see a lot of demo code displays from here: http://plugins.krajee.com/file-basic-usage-demo.
This is an enhanced HTML5 file input control, an extension of Bootstrap 3.x, implementing file upload preview, multi-file upload and other functions.
Generally speaking, we need to introduce the following two files for the plug-in to be used normally:
bootstrap-fileinput/css/fileinput.min.css
bootstrap-fileinput/js/fileinput.min.js
The simple interface effect is as follows. Like many upload file controls, it can accept various types of files. Of course, we can also specify the specific file type and other functions that are accepted.
If Chinese culture needs to be considered, then documents need to be introduced:
bootstrap-fileinput/js/fileinput_locale_zh.js
In this way, based on MVC's Bundles collection, we can add the files they need to the collection.
//Add support for bootstrap-fileinput control css_meteronic.Include("~/Content/MyPlugins/bootstrap-fileinput/css/fileinput.min.css"); js_meteronic.Include("~/Content/MyPlugins/bootstrap-fileinput/js/fileinput.min.js"); js_meteronic.Include("~/Content/MyPlugins/bootstrap-fileinput/js/fileinput_locale_zh.js"); js_meteronic.Include("~/Content/MyPlugins/bootstrap-fileinput/js/fileinput_locale_zh.js");In this way, we can present the Chinese interface description and prompts on the page, as shown in the following interface.
2. Use of File Input for File Upload
Generally speaking, we can define a general JS function to initialize this plug-in control, as shown in the following JS function code.
//Initialize the fileinput control (first initialization) function initFileInput(ctrlName, uploadUrl) { var control = $('#' + ctrlName); control.fileinput({ language: 'zh', //Set the language uploadUrl: uploadUrl, //Uploaded address allowedFileExtensions: ['jpg', 'png','gif'],//Received file suffix showUpload: false, //Does the upload button showCaption: false, //Does the title browser browserClass: "btn btn-primary", //Button style previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", });}In the page code, we place a file upload control, as shown in the following code.
<div style="height: 500px"> <input id="file-Portrait1" type="file"> </div>
In this way, the initialization code of our script code is as follows:
//Initialize the fileinput control (first initialization) initFileInput("file-Portrait", "/User/EditPortrait");This completes the initialization of the control. If we need to upload a file, then we also need JS code to handle the events uploaded by the client, and also need the MVC background controller to handle the file saving operation.
For example, my code for saving form data is as follows.
//Add record formValidate("ffAdd", function (form) { $("#add").modal("hide"); //Send construct parameters to the background var postData = $("#ffAdd").serializeArray(); $.post(url, postData, function (json) { var data = $.parseJSON(json); if (data.Success) { //Add portrait upload processing initPortrait(data.Data1); //Use the written ID to update $('#file-Portrait').fileinput('upload'); //Save successfully 1. Close the pop-up layer, 2. Refresh the table data showTips("Save successfully"); Refresh(); } else { showError("Save failed:" + data.ErrorMessage, 3000); } }).error(function () { showTips("You are not authorized to use this function, please contact the administrator to handle it."); }); }); });Among them, we noticed the processing logic code part of the file saving:
//Add the upload processing of portrait initPortrait(data.Data1);//Use the written ID to update $('#file-Portrait').fileinput('upload');The first line of code is to rebuild the uploaded additional content, such as the user's ID information, so that we can build some additional data based on these IDs for uploading and processing for the background.
This function mainly reassigns the ID to facilitate the acquisition of the latest additional parameters when uploading. This is the same as Uploadify processing mode.
//Initialize image information function initPortrait(ctrlName, id) { var control = $('#' + ctrlName); var imageurl = '/PictureAlbum/GetPortrait?id=' + id + '&r=' + Math.random(); //Important, it is necessary to update the additional parameter content of the control, and the image initialization display control.fileinput('refresh', { uploadExtraData: { id: id }, initialPreview: [ //Preview the image settings "<img src='" + imageurl + "' class='file-preview-image' alt='Portrait picture' title='Portrait Picture'>", ], }); }As we saw earlier, the address I uploaded is: "/User/EditPortrait". I will also announce this background function, hoping to give you a complete case code to learn.
/// <summary> /// Upload user avatar image/// </summary> /// <param name="id">User's ID</param> /// <returns></returns> public ActionResult EditPortrait(int id) { CommonResult result = new CommonResult(); try { var files = Request.Files; if (files != null && files.Count > 0) { UserInfo info = BLLFactory<User>.Instance.FindByID(id); if (info != null) { var fileData = ReadFileBytes(files[0]); result.Success = BLLFactory<User>.Instance.UpdatePersonImageBytes(UserImageType.PersonPortrait, id, fileData); } } } catch (Exception ex) { result.ErrorMessage = ex.Message; } return ToJsonContent(result); }In this way, we have built the above user portrait saving and processing logic, and the files can be saved normally to the background file system, and at the same time, some necessary information is recorded in the database.
Of course, in addition to using it to process user portrait pictures, we can also use it to build image album processing operations. The specific interface is as follows.
The initialization code for this part is as follows:
//Initialize the fileinput control (first initialization) $('#file-Portrait').fileinput({ language: 'zh', //Set the language uploadUrl: "/FileUpload/Upload", //Upload address allowedFileExtensions: ['jpg', 'png','gif'], //Received file suffix, maxFileCount: 100, enctype: 'multipart/form-data', showUpload: true, //Does the upload button showCaption: false, //Does the title browser browserClass: "btn btn-primary", //Button style previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", msgFilesTooMany: "The number of files selected to upload ({n}) exceeds the maximum allowed value {m}!", });The above is the detailed explanation of the experience of Bootstrap Metronic development framework introduced by the editor to you [Five] The usage of Bootstrap File Input file upload plug-in is explained in detail. I hope it will be helpful to everyone. If you want to know more information, please pay attention to the Wulin.com website!