Home > Web Front-end > JS Tutorial > Detailed explanation of JS file upload artifact bootstrap fileinput

Detailed explanation of JS file upload artifact bootstrap fileinput

高洛峰
Release: 2016-12-07 14:07:21
Original
2616 people have browsed it

The Bootstrap FileInput plug-in is so powerful that there is no reason not to use it. However, it is rare to find the complete usage method of this plug-in in China, so I went to its official website to translate the English documentation and put it here for students who are not good at English to refer to it. . Also attached is a piece of code sent by the caller and received by the servlet side, to be continued.

Detailed explanation of JS file upload artifact bootstrap fileinput

Introduction:

An enhanced HTML5 file input plugin for Bootstrap 3.x. This plug-in provides file preview for multiple types of files, and provides multiple selection and other functions. This plugin also provides you with an easy way to install an advanced file selection/upload control version to work with Bootstrap CSS3 styles. It greatly enhances the file input function by providing preview support for many types of files, such as pictures, text, html, video, sound, flash and objects. In addition, it also includes AJAX-based upload, drag and drop, and remove file functions, a visual upload progress bar, and an optional add or delete file preview function.

Tip: This plugin is dedicated to using a lot of css3 and html5 features under added jquery. Emphasis: you may find that css3 or html5 or a mixture of both are required in many implementations.

This plugin was first inspired by a blog post and Jasny'sFile Input plugin. However, this plug-in has now added many functions and enhancements, providing developers with a mature and complete file management tool and solution.

With the release of version 4.0.0, this plug-in now supports Ajax-based uploads using html5 Formdata and XHR2 protocols supported by a variety of modern browsers. And it also has native built-in support for AJAX-based file deletion on the server side. Therefore, it can add more powerful functions to add and remove files online. This plugin also adds drag-and-drop support for most modern browsers. It also already provides native support for Ajax uploads. In case, the browser does not support FormData or XHR2, this plug-in will downgrade to a normal form.

Introduction to the file upload plug-in File Input

Generally, we need to introduce the following two files for the plug-in to work properly:

bootstrap-fileinput/css/fileinput.min.css
bootstrap-fileinput/js/fileinput.min .js

The simple interface effect is the same as many upload file controls and can accept various types of files. Of course, we can also specify functions such as specific file types to be accepted.

Detailed explanation of JS file upload artifact bootstrap fileinput

If you need to consider Chinese culture, you also need to introduce the file:

bootstrap-fileinput/js/fileinput_locale_zh.js

In this MVC-based Bundles collection, we add the files they need to the collection. Can.

//添加对bootstrap-fileinput控件的支持
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");
Copy after login

In this way, we can present Chinese interface instructions and prompts on the page

Detailed explanation of JS file upload artifact bootstrap fileinput

Usage of the file upload plug-in File Input

Generally, we can define a common JS function , used to initialize this plug-in control, as shown in the following JS function code.

//初始化fileinput控件(第一次初始化)
function initFileInput(ctrlName, uploadUrl) {
 var control = $('#' + ctrlName);
 control.fileinput({
 language: 'zh', //设置语言
 uploadUrl: uploadUrl, //上传的地址
 allowedFileExtensions : ['jpg', 'png','gif'],//接收的文件后缀
 showUpload: false, //是否显示上传按钮
 showCaption: false,//是否显示标题
 browseClass: "btn btn-primary", //按钮样式
 previewFileIcon: "<i class=&#39;glyphicon glyphicon-king&#39;></i>",
 });
}
Copy after login

In 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>
Copy after login

The initialization code of our script code is as follows:

//初始化fileinput控件(第一次初始化)
initFileInput("file-Portrait", "/User/EditPortrait");
Copy after login

This completes the initialization of the control. If we need to upload files, we also need JS code to handle the events uploaded by the client. , and also requires the MVC background controller to handle the file save operation.

For example, my code for saving form data is as follows.

//添加记录的窗体处理
 formValidate("ffAdd", function (form) {
 $("#add").modal("hide");
 //构造参数发送给后台
 var postData = $("#ffAdd").serializeArray();
 $.post(url, postData, function (json) {
 var data = $.parseJSON(json);
 if (data.Success) {
 //增加肖像的上传处理
 initPortrait(data.Data1);//使用写入的ID进行更新
 $(&#39;#file-Portrait&#39;).fileinput(&#39;upload&#39;);
 //保存成功 1.关闭弹出层,2.刷新表格数据
 showTips("保存成功");
 Refresh();
 }
 else {
 showError("保存失败:" + data.ErrorMessage, 3000);
 }
 }).error(function () {
 showTips("您未被授权使用该功能,请联系管理员进行处理。");
 });
 });
Copy after login

Among them, we noticed the processing logic code part of file saving:

//增加肖像的上传处理
initPortrait(data.Data1);//使用写入的ID进行更新
$(&#39;#file-Portrait&#39;).fileinput(&#39;upload&#39;);
Copy after login

The first line of code is to reconstruct the uploaded additional content, such as the user's ID information, etc., so that we can based on These IDs are used to construct some additional data for background upload processing.

This function is mainly to reassign the ID to facilitate obtaining the latest additional parameters when uploading. This is the same as the processing mode of Uploadify.

//初始化图像信息
 function initPortrait(ctrlName, id) {
 var control = $(&#39;#&#39; + ctrlName);
 var imageurl = &#39;/PictureAlbum/GetPortrait?id=&#39; + id + &#39;&r=&#39; + Math.random();
 //重要,需要更新控件的附加参数内容,以及图片初始化显示
 control.fileinput(&#39;refresh&#39;, {
 uploadExtraData: { id: id },
 initialPreview: [ //预览图片的设置
 "<img src=&#39;" + imageurl + "&#39; class=&#39;file-preview-image&#39; alt=&#39;肖像图片&#39; title=&#39;肖像图片&#39;>",
 ],
 });
 }
Copy after login

As we saw earlier, the address I uploaded is: "/User/EditPortrait". I will also announce this background function, hoping to give everyone a complete case code study.

/// <summary>
 /// 上传用户头像图片
 /// </summary>
 /// <param name="id">用户的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.个人肖像, id, fileData);
 }
 }
 }
 catch (Exception ex)
 {
 result.ErrorMessage = ex.Message;
 }
 return ToJsonContent(result);
 }
Copy after login

In this way, we have constructed the above user portrait saving processing logic. The file can be saved to the background file system normally, and some necessary information is recorded in the database.

Of course, in addition to processing user portrait images, we can also use it to build image album processing operations.

//初始化fileinput控件(第一次初始化)
 $(&#39;#file-Portrait&#39;).fileinput({
 language: &#39;zh&#39;, //设置语言
 uploadUrl: "/FileUpload/Upload", //上传的地址
 allowedFileExtensions : [&#39;jpg&#39;, &#39;png&#39;,&#39;gif&#39;],//接收的文件后缀,
 maxFileCount: 100,
 enctype: &#39;multipart/form-data&#39;,
 showUpload: true, //是否显示上传按钮
 showCaption: false,//是否显示标题
 browseClass: "btn btn-primary", //按钮样式
 previewFileIcon: "<i class=&#39;glyphicon glyphicon-king&#39;></i>",
 msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
 });
Copy after login


Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template