bootstrap fileinput upload plug-in

Keywords: Excel github JSON Attribute

Foreword: The previous three articles introduced some common usage of bootstrap table, and found that bloggers were fascinated by this flat style. Two days ago, I did an excel import function. The front end used the original input type='file'tag. The effect could not bear to look directly. So the blogger decided to find a good upload component to replace it. Since bootstrap is open source, there must be many components about it in the community, and there must be such common upload components as well. After some searching, the blogger found this component: bootstrap fileinput. About the simple application of this component, blog Garden Daniel Wu Hua Chun Wrote an article Experience Summary of Bootstrap Development Framework Based on Metronic (5) -- Bootstrap File Upload Plug-in Use of Input However, many details are not involved, so after completing the development task, the blogger summarizes some common usage of this component. In this record, even if you take a note, it will also provide some convenience for friends 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 Show: http://plugins.krajee.com/file-basic-usage-demo

I. Effect demonstration

1. The original input type='file', simply can't bear to look straight at.

2. Bootstrap fileinput without any decoration: (bootstrap fileinput primary evolution)

3. bootstrap fileinput Advanced Evolution: Chinese Culture, Drag-and-Drop Upload, File Extension Check (No upload if not required)

Drag and drop uploads

Uploading

4. bootstrap fileinput evolves to allow simultaneous multithreading of multiple files.

Uploading

Upload completed

Code examples

  What about? What's the effect? Don't worry, we will achieve the above effect step by step.

1. cshtml page

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 choose Excel file</h4>
                </div>
                <div class="modal-body">
                    <a href="~/Data/ExcelTemplate/Order.xlsx" 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>

Focus on this sentence:

<input type="file" name="txt_file" id="txt_file" multiple class="file-loading" />

Multiple means that multiple files are allowed to be uploaded at the same time, and class="file-loading" means the style of the label. It's important here that if class="file", the culture doesn't work.

2. js initialization

$(function () {
    //0. Initialize fileinput
    var oFileInput = new FileInput();
    oFileInput.Init("txt_file", "/api/OrderApi/ImportOrder");
});
//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', //Setup language
        uploadUrl: uploadUrl, //Upload address
        allowedFileExtensions: ['jpg', 'gif', 'png'],//Received file suffixes
        showUpload: true, //Whether to display the upload button
        showCaption: false,//Whether to display the title or not
        browseClass: "btn btn-primary", //Button style     
        //DropZone Enabled: false, // whether to display drag area
        //minImageWidth: 50, // Minimum Width of Picture
        //minImageHeight: 50, // Minimum Height of Picture
        //maxImageWidth: 1000, // Maximum Width of Picture
        //maxImageHeight: 1000, // Maximum height of the image
        //maxFileSize: 0, // in kb, if 0 means no limit on file size
        //minFileCount: 0,
        maxFileCount: 10, //Represents the maximum number of files allowed to upload at the same time
        enctype: 'multipart/form-data',
        validateInitialCount:true,
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
        msgFilesTooMany: "Select the number of files to upload({n}) Exceeding the maximum allowable value{m}!",
    });

    //Events after the completion of import file upload
    $("#txt_file").on("fileuploaded", function (event, data, previewId, index) {
        $("#myModal").modal("hide");
        var data = data.response.lstOrderImport;
        if (data == undefined) {
            toastr.error('Incorrect file format type');
            return;
        }
        //1. Initialization table
        var oTable = new TableInit();
        oTable.Init(data);
        $("#div_startimport").show();
    });
}
    return oFile;
};

Explain:

(1) The fileinput() method passes in a json data, which has many attributes. Each attribute represents the characteristics of initializing the upload control. If none of these attributes are set, the default settings are used. If you want to see what attributes are in it, you can open the source code of fileinput.js, as shown in the last figure:

If these properties are not specifically set, the default values are used.

(2) $(" txt_file").on("fileuploaded", function (event, data, previewId, index) {} registers the callback event after the upload is completed. That is to say, the day after tomorrow, the uploaded files will be processed in this method.

3. Background C# Corresponding Method

Remember that there is a parameter url in the method fileinput() of the initialization control in js, and the corresponding value of this url indicates the corresponding processing method of C# the day after tomorrow. Still stick out the background processing method.

     [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 ? 0 : iMax_Import_Index.Value;
            #endregion

            #region 1. Getting Workbook Objects 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 { };
            }

            //Processing the logic of excel


            //orderManager.Add(lstOrder);
            lstOrderImport = lstOrderImport.OrderBy(x => x.IMPORT_STATU).ToList();
            return new { lstOrderImport = lstOrderImport };
        }

Because the blogger's project is to upload excel, the logic of NPOI is used here. If you upload pictures and other files, you can use GDI to process pictures.

4. Upload multiple files at the same time

When uploading multiple files at the same time, the front desk will send multiple asynchronous requests to the background, that is, when uploading three files at the same time, the background ImportOrder method will enter three times. This allows you to use multithreading to process three files at the same time.

Three, summary

The basic usage of bootstrap fileinput is probably finished. It is actually an uploaded component, and there is no advanced usage. The key point is to make the interface more friendly and better increase the user experience.


2015-12-01

After two hours of busy work this morning, the source code was finally sorted out. Interested download to see. Source download.


This article is reproduced in: http://www.cnblogs.com/landeanfen/p/5007400.html

This is the original code. The java background I use and some bug s on the way are introduced in the next article.~

Posted by pixelsoul on Fri, 29 Mar 2019 10:03:30 -0700