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

Analysis of JS file upload artifact bootstrap fileinput

不言
Release: 2018-06-25 17:40:47
Original
2400 people have browsed it

This article mainly introduces the JS file upload artifact Bootstrap FileInput. The style is very beautiful and supports uploaded file preview, ajax synchronous or asynchronous upload, drag and drop file upload and other cool functions. It has certain reference value. If you are interested, Friends, you can refer to the

Bootstrap FileInput plug-in. It 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. I 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.

Introduction:

An enhanced HTML5 file input plug-in 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.

Tips: This plug-in is dedicated to using a large number of css3 and html5 functions under added jquery. Emphasis: You may find css3 or html5 or both. Mixing is 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 before the plug-in can be used normally:

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

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

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 can just add the files they need to the collection.

//添加对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

Usage of file upload plug-in File Input

Generally, we can define a general JS function to initialize the 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.

<p class="row" style="height: 500px">
<input id="file-Portrait1" type="file">
</p>
Copy after login

The initialization code of our script code is as follows:

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

This is complete After the control has been initialized, if we need to upload a file, we need JS code to handle the client upload event, and we also need the MVC background controller to handle the file saving 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

We noticed the processing logic code part for 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 construct some additional data based on these IDs 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

We saw earlier that 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

这样我们就构建了上面的用户肖像的保存处理逻辑了,文件可以正常的保存到后台的文件系统里面,同时数据库里面记录一些必备的信息。

当然,除了用来处理用户的肖像图片,我们也可以用来构建图片相册的处理操作的。

//初始化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

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

jQuery和CSS3实现仿花瓣网固定顶部位置带悬浮效果的导航菜单

js中实现限制uploadify的上传个数

The above is the detailed content of Analysis of JS file upload artifact bootstrap fileinput. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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