One, the effect shows
1, the original input type= ' file ', simply can't bear to look straight.
2, do not do any decoration of the bootstrap Fileinput: (Bootstrap fileinput primary evolution)
3, Bootstrap Fileinput Advanced Evolution: Chinese culture, can drag and drop upload, file expansion of the famous school inspection (if not the need for files, not to upload)
Drag and drop upload
Upload in
4, Bootstrap Fileinput Evolution: Allow simultaneous multithreading upload multiple files.
Upload in
After the upload is complete
Second, the code example
1, cshtml page
First, the required JS and CSS files are introduced.
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" > &times;</span></button>
<h4 class= "Modal-title" id= "Mymodallabel" > Please select 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 indicates that multiple files are allowed to be uploaded at the same time, class= "file-loading" represents the style of the label.
2. JS Initialization
$ (function () {
0. Initialization of 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: ' en ',//Set language
Uploadurl:uploadurl,//uploaded address
Allowedfileextensions: [' jpg ', ' gif ', ' PNG '],//received file suffix
Showupload:true,//whether to show the upload button
showcaption:false,//whether the caption is displayed
Browseclass: "Btn btn-primary",//button style
dropzoneenabled:false,//whether to show drag areas
MINIMAGEWIDTH:50,//minimum width of picture
minimageheight:50,//The minimum height of a picture
maximagewidth:1000,//the maximum width of a picture
Maximum height of maximageheight:1000,//picture
maxfilesize:0,//Unit is KB, if 0 indicates no limit to file size
minfilecount:0,
Maxfilecount:10,//indicates the maximum number of files allowed to be uploaded simultaneously
Enctype: ' Multipart/form-data ',
Validateinitialcount:true,
Previewfileicon: "<i class= ' Glyphicon glyphicon-king ' ></i>",
Msgfilestoomany: "The number of files selected for upload ({n}) exceeds the maximum allowed value {m}! ",
});
Events after the import file has finished uploading
$ ("#txt_file"). On ("fileuploaded", function (event, data, Previewid, index) {
$ ("#myModal"). Modal ("Hide");
var data = Data.response.lstOrderImport;
if (data = = undefined) {
Toastr.error (' file format type is incorrect ');
Return
}
1. Initialize the table
var otable = new Tableinit ();
Otable.init (data);
$ ("#div_startimport"). Show ();
});
}
return ofile;
};
Description
(1) The Fileinput () method contains a JSON data that has many attributes, each representing the attributes of the initialization upload control, or the default setting if none of the properties are set. If the park friends want to see what properties it has, you can open the Fileinput.js source, in its final picture:
These properties use the default values if they are not set intentionally.
(2) $ ("#txt_file"). On ("fileuploaded", function (event, data, Previewid, index) {} This method registers the callback event after the upload completes. That is, after processing the uploaded file, enter this method inside processing.
3, the background C # corresponding method
Remember to initialize the control method in JS Fileinput () Inside has a parameter URL, the corresponding value of this URL indicates C # acquired corresponding processing method. or post the background of the 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. Get 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 {};
}
//............... Handling 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, so here is used with the logic of the Npoi, if you are uploading pictures and other documents, you can use GDI to process pictures.
4. Upload multiple files at the same time
Upload 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 of the Importorder method will enter three times. This allows you to use multithreading to process three files at the same time.
Third, summary
About the basic use of bootstrap fileinput is about to be introduced, in fact, is an upload component, there is no advanced usage. The point is to make the interface more user-friendly and to better enhance the user experience.
The use of file input of bootstrap files uploading plugin
1, file Upload plug-in files input introduction
This plugin homepage address is: Http://plugins.krajee.com/file-input, can see a lot of demo code show here: Http://plugins.krajee.com/file-basic-usage-demo.
This is an enhanced HTML5 file input control, is a Bootstrap 3.x extension, to achieve file upload Preview, multiple file upload functions.
In general, we need to introduce the following two files, the plug-in to normal use:
Bootstrap-fileinput/css/fileinput.min.css
Bootstrap-fileinput/js/fileinput.min.js
The simple interface effect is as follows, and as with many upload file controls, you can accept various types of files. Of course, we can also specify features such as file types that are specifically accepted.
If you need to consider the culture, then you need to introduce the file:
Bootstrap-fileinput/js/fileinput_locale_zh.js
So based on the MVC bundles Collection, we add the files they need to the collection.
Adding support for Bootstrap-fileinput controls
Css_metronic. Include ("~/content/myplugins/bootstrap-fileinput/css/fileinput.min.css");
Js_metronic. Include ("~/content/myplugins/bootstrap-fileinput/js/fileinput.min.js");
Js_metronic. Include ("~/content/myplugins/bootstrap-fileinput/js/fileinput_locale_zh.js");
So we are in the page, we can present the Chinese interface description and hints, as shown in the following interface.
2, File upload plug-in files input use
In general, we can define a common function of JS to initialize the plug-in control, as shown in the function code for the following JS.
Initialize the Fileinput control (first initialization)
function Initfileinput (ctrlname, Uploadurl) {
var control = $ (' # ' + ctrlname);
Control.fileinput ({
Language: ' en ',//Set language
Uploadurl:uploadurl,//uploaded address
Allowedfileextensions: [' jpg ', ' png ', ' gif '],//received file suffix
Showupload:false,//whether to show the upload button
showcaption:false,//whether the caption is displayed
Browseclass: "Btn btn-primary",//button style
Previewfileicon: "<i class= ' Glyphicon glyphicon-king ' ></i>",
});
}
Inside the page code, we place a file upload control, as shown in the following code.
<div class= "Row" style= "height:500px" >
<input id= "file-portrait1" type= "File" >
</div>
So the initialization code for our scripting code is as follows:
Initialize the Fileinput control (first initialization)
Initfileinput ("file-portrait", "/user/editportrait");
This completes the control initialization, if we need to upload files, then we need JS code to handle the client upload events, but also need the MVC background controller to handle file save operations.
For example, my code to save the form data is shown below.
Add a record to a form handle
Formvalidate ("Ffadd", function (form) {
$ ("#add"). Modal ("Hide");
The construction parameters are sent to the background
var postdata = $ ("#ffAdd"). Serializearray ();
$.post (URL, postdata, function (JSON) {
var data = $.parsejson (JSON);
if (data. Success) {
Increase the image upload processing
Initportrait (data. DATA1);//update with the written ID
$ (' #file-portrait '). Fileinput (' upload ');
Save Success 1. Close the pop-up layer, 2. Refresh table Data
Showtips ("Save Success");
Refresh ();
}
else {
ShowError ("Save failed:" + data.) ErrorMessage, 3000);
}
}). Error (function () {
Showtips ("You are not authorized to use this feature, please contact your administrator for processing.") ");
});
});
Where we note the part of the processing logic code for the file Save:
Increase the image upload processing
Initportrait (data. DATA1);//update with the written ID
$ (' #file-portrait '). Fileinput (' upload ');
The first line of code is to rebuild the additional content of the upload, such as the user ID information, so that we can build some additional data based on these IDs to the background upload processing.
This function is to assign a value to the ID, to facilitate the upload, get the latest additional parameters, this and uploadify processing mode.
Initializing image information
function initportrait (ctrlname, id) {
var control = $ (' # ' + ctrlname);
var imageurl = '/picturealbum/getportrait?id= ' + ID + ' &r= ' + math.random ();
Important, you need to update the control's additional parameter content, and the image initialization display
Control.fileinput (' Refresh ', {
Uploadextradata: {Id:id},
Initialpreview: [//Preview picture settings
"<img src= '" + ImageUrl + "' class= ' file-preview-image ' alt= ' portrait picture ' title= ' portrait image ' > ',
],
});
}
Before we see, I uploaded the address for: "/user/editportrait", this backstage function I also announced, I hope to give you a complete case code learning.
<summary>
Upload User avatar Picture
</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. Personal portrait, id, filedata);
}
}
}
catch (Exception ex)
{
Result. ErrorMessage = ex. message;
}
return tojsoncontent (Result);
}
In this way we build the above user portrait of the Save processing logic, the file can be stored in the background of the file system, while the database records some of the necessary information.
Of course, in addition to processing the image of the user, we can also be used to build photo albums processing operations, the specific interface is as follows.
The initialization code for this section looks like this:
Initialize the Fileinput control (first initialization)
$ (' #file-portrait '). Fileinput ({
Language: ' en ',//Set language
Uploadurl: "/fileupload/upload",//uploaded address
Allowedfileextensions: [' jpg ', ' png ', ' gif '],//received file suffix,
MAXFILECOUNT:100,
Enctype: ' Multipart/form-data ',
Showupload:true,//whether to show the upload button
showcaption:false,//whether the caption is displayed
Browseclass: "Btn btn-primary",//button style
Previewfileicon: "<i class= ' Glyphicon glyphicon-king ' ></i>",
Msgfilestoomany: "The number of files selected for upload ({n}) exceeds the maximum allowed value {m}! ",
});