Analysis of JS file upload artifact bootstrap fileinput
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");
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='glyphicon glyphicon-king'></i>", }); }
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>
The initialization code of our script code is as follows:
//初始化fileinput控件(第一次初始化) initFileInput("file-Portrait", "/User/EditPortrait");
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进行更新 $('#file-Portrait').fileinput('upload'); //保存成功 1.关闭弹出层,2.刷新表格数据 showTips("保存成功"); Refresh(); } else { showError("保存失败:" + data.ErrorMessage, 3000); } }).error(function () { showTips("您未被授权使用该功能,请联系管理员进行处理。"); }); });
We noticed the processing logic code part for file saving:
//增加肖像的上传处理 initPortrait(data.Data1);//使用写入的ID进行更新 $('#file-Portrait').fileinput('upload');
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 = $('#' + ctrlName); var imageurl = '/PictureAlbum/GetPortrait?id=' + id + '&r=' + Math.random(); //重要,需要更新控件的附加参数内容,以及图片初始化显示 control.fileinput('refresh', { uploadExtraData: { id: id }, initialPreview: [ //预览图片的设置 "<img src='" + imageurl + "' class='file-preview-image' alt='肖像图片' title='肖像图片'>", ], }); }
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); }
这样我们就构建了上面的用户肖像的保存处理逻辑了,文件可以正常的保存到后台的文件系统里面,同时数据库里面记录一些必备的信息。
当然,除了用来处理用户的肖像图片,我们也可以用来构建图片相册的处理操作的。
//初始化fileinput控件(第一次初始化) $('#file-Portrait').fileinput({ language: 'zh', //设置语言 uploadUrl: "/FileUpload/Upload", //上传的地址 allowedFileExtensions : ['jpg', 'png','gif'],//接收的文件后缀, maxFileCount: 100, enctype: 'multipart/form-data', showUpload: true, //是否显示上传按钮 showCaption: false,//是否显示标题 browseClass: "btn btn-primary", //按钮样式 previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!", });
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
jQuery和CSS3实现仿花瓣网固定顶部位置带悬浮效果的导航菜单
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!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools