Summary of techniques for implementing file upload in ajax html
This article mainly summarizes the file uploading techniques based on ajax html in detail. It has a certain value for reference and learning ajax, and I have some feelings about ajax Interested friends can refer to the quote
: As we all know, uploading files in HTML requires only one input, type=file. However, the style of this label is really not worth mentioning. It is probably difficult to change its style. But it’s actually quite simple. Let’s talk about some tips for uploading files today!
1. How to customize the style?
1) Just define it according to the style you like to see, such as , it can be The background image effect can be a text instruction. In short, you can change it however you want! With the button, a file name container is also needed to store the name when selecting the file to upload, so as to prevent the upload from looking boring and difficult to understand.
2), add the file control that really needs to be uploaded, and set the attribute display:none; such as , so that there is a real uploaded file place. So, it can be said that how beautiful the interface for uploading files is depends on your imagination!
2. How to trigger an event?
This is an important point. The triggering point should be the style you write, but the element that really works is hidden, but it does not affect its click effect. You only need to give It just triggers a click event, such as $('#target-file').trigger('click');
3. Multiple-select files?
To upload multiple files, just use multiple=true of a file in HTML. Of course, you can also choose a third-party upload control, such as swfupload. The effect is really good. But for people who don’t want to use the plug-in, it won’t work.
Interface beautification can actually use plug-ins such as jqueryui; If you want to do some friendly interactions, ajax technology will be used, no refresh switching, asynchronous upload, submission, and finally, in fact, The path of ajax can also be retained. Use pushState and replaceState to implement pjax.
Form verification: validform.js
Friendly pop-up prompt: layer.js
5. Any compatibility issues?
When doing interface work, the most feared and important thing is the compatibility issue between various browsers. The following are the main points for reference:
select, input display height is inconsistent;
alert pop-up window is inconsistent;
6. Demo code
##<a href="javascript:;" up-type-id="1" class="btn btn-default small-btn switch-upload-method"><span>本地上传</span></a>
<a href="javascript:;" up-type-id="2" class="upload-file-instead btn btn-default small-btn switch-upload-method"><span>打包工具</span></a>
<input type="file" name="apkFiles[]" id="local-upload-real-file" class="upload-file-real hide" response-id="local-upload-container" multiple='true' />
<input type="file" name="apkToolFiles[]" id="apk-tool-real-file" class="upload-file-real hide" response-id="apk-tool-container-textarea" />
<script>
$(function(){
var alertTitle = '系统提示:';
var submitId = '#do-submit';
$('#taskForm').Validform({
btnSubmit: submitId,
tiptype: 1,
ignoreHidden: true,
dragonfly: false,
tipSweep: true,
label: ".label",
showAllError: false,
postonce: true,
ajaxPost: true,
datatype:{
},
beforeCheck:function(curform){
},
beforeSubmit:function(curform){
$('.upload-file-real').attr('disabled', 'disabled');
$(submitId).attr('disabled', 'disabled'); //提交前禁用按钮
ajaxSubmitForm(curform);
$(submitId).removeAttr('disabled'); //失败后恢复可提交
return false;
},
submitForm: function(){} //不再起作用
});
//切换上传方法
$('.switch-upload-method').off().on('click', function(){
// $(submitId).attr('disabled', 'disabled');
var pObj = $(this).parent().find('.switch-upload-method');
var index = pObj.index(this);
var uploadTypeId = $('#upload-type-id').val(); //上传方式:1:打包工具;2:本地上传,0:没有上传方式
var uploadType = $(this).attr('up-type-id');
if(parseInt($('#sub-channel-count').html()) > 0){
if(uploadTypeId != uploadType){
layer.alert('还有子渠道包数据,不能完成切换,请先确认清除再切换!');
return false;
}
}
pObj.not(':eq(' + index + ')').removeClass('btn-danger').addClass('btn-default');
pObj.eq(index).removeClass('btn-default').addClass('btn-danger');
if(uploadType == 36){ //local-upload
$('#upload-type-id').val(uploadType);
$('#init-apk-container').show();
$('#apk-tool-container').hide();
$('#upload-main-control').find('.del-it-main').css({display: 'inline-block'});
$('#local-upload-real-file').trigger('click');
}else if(uploadType == 35){ //apk-tool
$('#upload-type-id').val(uploadType);
$('#init-apk-container').hide();
$('#local-upload-container').hide();
$('#upload-main-control').find('.del-it-main').hide();
$('#apk-tool-container').show();
}
});
//本地上传
$('#local-upload-real-file').off().on('change', function(){
if(!$(this).val()){
return false;
}
file_size = 0;
filepath = $(this).val();
maxFileSize = 30 * 1024 * 1024;
var browserCfg = {};
var ua = window.navigator.userAgent;
if (ua.indexOf("MSIE") >=1 ){
browserCfg.ie = true;
}else if(ua.indexOf("Firefox") >=1 ){
browserCfg.firefox = true;
}else if(ua.indexOf("Chrome") >=1 ){
browserCfg.chrome = true;
}
if (browserCfg.ie) {
var img = new Image();
img.src = filepath;
file_size = img.fileSize;
while (true) {
if (img.fileSize > 0) {
if (img.fileSize > maxFileSize) {
alert("上传包超过30MB限制,请使用打包工具上传!");
return false;
}
break;
}
}
} else {
file_size = this.files[0].size;
if (file_size > maxFileSize) {
alert("上传包超过30MB限制,请使用打包工具上传!");
return false;
}
}
var responseObjId = $(this).attr('response-id');
var responseObj = $('#' + responseObjId);
$('#taskForm').ajaxSubmit({
url:'/aa/bb/uploadTmpApk',
resetForm: false,
dataType: 'json',
beforeSubmit: function(option){
window.loading = layer.load(2);
},
success: function(data, statusText){
layer.close(window.loading);
if(data.status == 1){
$('#version-identifier').val(data.version);
responseObj.html(data.apkInfoHtml);
responseObj.show();
var delObj = $('#upload-main-control').find('.del-it-main');
delObj.css({'display': 'inline-block'});
$('#sub-channel-count').html(data.apkTotal);
$('#init-apk-container').hide();
$(submitId).removeAttr('disabled');
}else{
layer.alert(data.info, {title: alertTitle});
}
},
error: function(data){
layer.close(window.loading);
layer.alert('未知错误,请稍后再试!');
}
});
return false;//防止dialog 自动关闭
});
//打包工具
$('#apk-tool-real-file').off().on('change', function(){
if(!$(this).val()){
return false;
}
var responseObjId = $(this).attr('response-id');
var responseObj = $('#' + responseObjId);
$('#Form').ajaxSubmit({
url:'/aa/bb/uploadTmpApkTool',
resetForm: false,
dataType: 'json',
beforeSubmit: function(option){
window.loading = layer.load(2);
},
success: function(data, statusText){
layer.close(window.loading);
if(data.status == 1){
$('#version-identifier').val(data.version);
responseObj.html(data.infoHtml);
var parentContainer = responseObj.parent().parent(),
nameContainer = parentContainer.find('.apk-name-container'),
delObj = parentContainer.find('.del-it-apk-tool');
nameContainer.html(data.apkName);
nameContainer.attr('title', data.apkName);
$('#apk-tool-file-tmp').html(data.fileInfo);
$(submitId).removeAttr('disabled');
}else{
layer.alert(data.info, {title: alertTitle});
}
},
error: function(data){
layer.close(window.loading);
layer.alert('未知错误,请稍后再试!');
}
});
return false;//防止dialog 自动关闭
});
$('.apk-tool-upload-button').on('click', function(){
$('#apk-tool-real-file').trigger('click');
});
});
</script>
The above is mainly about using the hidden input file tag selection, ajax submission immediately after selecting the file, and finally, the entire form ajax submission process. Use some css and js reasonably to make your web page more free!
Related recommendations:
HTML5-based previewable multi-image Ajax upload
PHP similar Simple example of AJAx uploading pictures
Parammeter submission does not update during ajax upload and other related issues
The above is the detailed content of Summary of techniques for implementing file upload in ajax html. For more information, please follow other related articles on the PHP Chinese website!

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack 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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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.

SublimeText3 Chinese version
Chinese version, very easy to use

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