English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Preface:
The previous three articles introduced some common usages of bootstrap table, and it was found that the blogger is somewhat obsessed with this flat style. The other day, I was working on a function to import Excel files, using the original input type='file' tag on the front end, which was not pleasing to the eye, so the blogger decided to find a nice upload component to replace it. Since bootstrap is open source, the community must have many components about it, and there must also be this common upload component. After a lot of searching, as the saying goes, 'effort is rewarded', the blogger finally found this component: bootstrap fileinput. This article will detail the usage of this component based on the experience of developing with the BootStrap Metronic framework, just that many details were not covered. Therefore, the blogger summarized some common usages of this component during the development process. This is recorded here, not only as a note but also to provide convenience for those who need to use it.
Source code and API address:
bootstrap-fileinput source code:https://github.com/kartik-v/bootstrap-fileinput
bootstrap-fileinput online API:http://plugins.krajee.com/file-input
bootstrap-fileinput Demo display:http://plugins.krajee.com/file-basic-usage-demo
First, Effect Display
1Second, The original input type='file' is simply unbearable.
2Second, Unadorned Bootstrap fileinput: (Bootstrap fileinput basic evolution)
3Second, Bootstrap fileinput advanced evolution: Chinese localization, drag and drop upload, file extension validation (if it is not the required file, it will not be uploaded)
Drag and drop upload
Uploading
4Second, Bootstrap fileinput ultimate evolution: allows multiple file uploads in multi-threading.
Uploading
After uploading
Second, Code Example
How is it? How do you feel? Don't worry, we will implement the above effects step by step.
1page
First, introduce the required js and css files.
//bootstrap fileinput bundles.Add(new ScriptBundle("~/Content/bootstrap-fileinput/js").Include( "~/Content/bootstrap-fileinput/js/fileinput.min.js", "~/Content/bootstrap-fileinput/js/fileinput_locale_zh.js")); bundles.Add(new StyleBundle("~/Content/bootstrap-fileinput/css").Include( "~/Content/bootstrap-fileinput/css/fileinput.min.css"); @Scripts.Render("~/Content/bootstrap-fileinput/js") @Styles.Render("~/Content/bootstrap-fileinput/css")
Then define the input type='file' tag
<form> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel">Please select an Excel file</h4> </div> <div class="modal-body"> <a href="~/Data/ExcelTemplate/Order.xlsx" rel="external nofollow" class="form-control" style="border:none;">Download import template</a> <input type="file" name="txt_file" id="txt_file" multiple class="file-loading" /> </div></div> </div> </div> </form>
Pay attention to this sentence:
<input type="file" name="txt_file" id="txt_file" multiple class="file-loading" />
multiple indicates that multiple files can be uploaded at the same time, class="file"-"loading" indicates the style of the label. This is very important, if class="file", the Chinese localization cannot take effect.
2、js initialization
$(function () { //0. Initialize fileinput var oFileInput = new FileInput(); oFileInput.Init("txt_file", "/api/OrderApi/ImportOrder"); });<span class="cnblogs_code_copy"></span> <span class="cnblogs_code_copy"></span> //Initialize fileinput var FileInput = function () { var oFile = new Object(); //Initialize the fileinput control (first initialization) oFile.Init = function(ctrlName, uploadUrl) { var control = $('#' + ctrlName); //Initialize the style of the upload control control.fileinput({ language: 'zh', //Set language uploadUrl: uploadUrl, //The upload address allowedFileExtensions: ['jpg', 'gif', 'png'],//Accepted file extensions showUpload: true, //Whether to display the upload button showCaption: false,//Whether to display the title browseClass: "btn btn-primary", //Button style //dropZoneEnabled: false,//Whether to display the drag area //minImageWidth: 50, //The minimum width of the image //minImageHeight: 50,//The minimum height of the image //maxImageWidth: 1000,//The maximum width of the image //maxImageHeight: 1000,//The maximum height of the image //maxFileSize: 0,//Unit is kb, if 0, it means no file size limit //minFileCount: 0, maxFileCount: 10, //It indicates the maximum number of files that can be uploaded at the same time enctype: 'multipart/form-data', validateInitialCount: true, previewFileIcon: "<i class='glyphicon glyphicon-king'></i>" msgFilesTooMany: "The number of selected files ({n}) exceeds the maximum allowed value {m}!", }); //Event after file upload is completed $("#txt_file").on("fileuploaded", function (event, data, previewId, index) { $("#myModal").modal("hide"); var data = data.response.lstOrderImport; if (data == undefined) { toastr.error('The file format type is incorrect'); return; //1.Initialize the table var oTable = new TableInit(); oTable.Init(data); $("#div_startimport").show(); }); return oFile; };
Description:
(1The fileinput() method takes a JSON data as input, which contains many properties. Each property represents the characteristics when initializing the upload control. If these properties are not set, it means the default settings are used. If friends want to see what properties it contains, they can open the source code of fileinput.js, at the end as shown in the figure:
These properties will use the default values if not specifically set.
(2)$("#txt_file").on("fileuploaded", function (event, data, previewId, index) {} This method registers the callback event after the upload is completed. It is the method that enters after the file upload is processed on the backend.
3Corresponding method in backend C#
Remember that in the fileinput() initialization method in js, there is a parameter called url, the value of which indicates the corresponding handling method in the C# backend. Let's post the handling method on the backend.
[ActionName("ImportOrder")] public object ImportOrder() { var oFile = HttpContext.Current.Request.Files["txt_file"]; var lstOrderImport = new List<DTO_TO_ORDER_IMPORT>(); #region 0. Data Preparation var lstExistOrder = orderManager.Find(); var lstOrderNo = lstExistOrder.Select(x => x.ORDER_NO).ToList(); var lstTmModel = modelManager.Find(); var lstTmMaterial = materialManager.Find(); //var iMax_Import_Index = lstExistOrder.Max(x => x.IMPORT_INDEX); //iMax_Import_Index = iMax_Import_Index == null ?63; 0 : iMax_Import_Index.Value; #endregion #region 1Obtained Workbook object through Stream IWorkbook workbook = null; if (oFile.FileName.EndsWith(".xls")) { workbook = new HSSFWorkbook(oFile.InputStream); else if (oFile.FileName.EndsWith(".xlsx")) { workbook = new XSSFWorkbook(oFile.InputStream); if (workbook == null) { return new { }; //...............The logic of processing excel //orderManager.Add(lstOrder); lstOrderImport = lstOrderImport.OrderBy(x => x.IMPORT_STATU).ToList(); return new { lstOrderImport = lstOrderImport };
Since the blogger's project is to upload excel, NPOI logic is used here. If you upload images or other files, you can use GDI to handle images.
4Uploading multiple files at the same time
When uploading multiple files at the same time, the front-end will send multiple asynchronous requests to the back-end, which means that when three files are uploaded at the same time, the ImportOrder method of the back-end will enter three times. This can use multi-threading to process three files at the same time.
Summary
That's about it for the basic usage of bootstrap fileinput. It's just a component for uploading, and there's no advanced usage. The key is to make the interface more user-friendly and improve the user experience. If you have any questions, please leave a message, and the editor will reply to you in time. I am also very grateful for the support of everyone for the Yell Tutorial website!
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liabilities. If you find any content suspected of copyright infringement, please send an email to notice#w.3Please send an email to codebox.com (replace # with @ when sending an email) to report violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.