Home Web Front-end JS Tutorial What are the steps to easily implement file upload with ajax+html?

What are the steps to easily implement file upload with ajax+html?

Apr 24, 2018 pm 05:00 PM
upload document

This time I will bring you how to easily implement ajax html File uploadWhat are the steps, what are the notesWhat are the steps to easily implement ajax html to upload files, the following is a practical case, let’s take a look take a look.

Quotation: Everyone knows that 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 < /a>, it can be a background image effect, it 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. The element that actually works is hidden, but it does not affect its click effect. You only need to trigger a Just click on the event, such as $('#target-file').trigger('click');

3. Select multiple 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 those who don’t want to If you use the plug-in, it won't work.                                                                                      

Interface beautification

In fact, you can 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, Finally, in fact, the path of ajax can also be retained. Use pushState and replaceState to implement pjax.Form verification
: validform.js
Asynchronous submission of files: jquery.form.jsFriendly 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:

table The processing method of width is inconsistent;

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=&#39;true&#39; />
<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>
Copy after login
The above is mainly to use 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!

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of Ajax() to interact with the background


Detailed explanation of methods for handling WebService cross-domain issues

The above is the detailed content of What are the steps to easily implement file upload with ajax+html?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to recover expired WeChat files? Can expired WeChat files be recovered? How to recover expired WeChat files? Can expired WeChat files be recovered? Feb 22, 2024 pm 02:46 PM

Open WeChat, select Settings in Me, select General and then select Storage Space, select Management in Storage Space, select the conversation in which you want to restore files and select the exclamation mark icon. Tutorial Applicable Model: iPhone13 System: iOS15.3 Version: WeChat 8.0.24 Analysis 1 First open WeChat and click the Settings option on the My page. 2 Then find and click General Options on the settings page. 3Then click Storage Space on the general page. 4 Next, click Manage on the storage space page. 5Finally, select the conversation in which you want to recover files and click the exclamation mark icon on the right. Supplement: WeChat files generally expire in a few days. If the file received by WeChat has not been clicked, the WeChat system will clear it after 72 hours. If the WeChat file has been viewed,

Photos cannot open this file because the format is not supported or the file is corrupted Photos cannot open this file because the format is not supported or the file is corrupted Feb 22, 2024 am 09:49 AM

In Windows, the Photos app is a convenient way to view and manage photos and videos. Through this application, users can easily access their multimedia files without installing additional software. However, sometimes users may encounter some problems, such as encountering a "This file cannot be opened because the format is not supported" error message when using the Photos app, or file corruption when trying to open photos or videos. This situation can be confusing and inconvenient for users, requiring some investigation and fixes to resolve the issues. Users see the following error when they try to open photos or videos on the Photos app. Sorry, Photos cannot open this file because the format is not currently supported, or the file

Preparing for removal takes a long time in Windows 11/10 Preparing for removal takes a long time in Windows 11/10 Feb 19, 2024 pm 07:42 PM

In this article, we will introduce how to solve the problem of "Ready to delete" prompt when deleting files or folders in Windows system. This prompt means that the system is performing some background operations, such as checking file permissions, verifying whether the file is occupied by other programs, calculating the size of the item to be deleted, etc. We will provide you with some workarounds to ensure that you can successfully delete your files without waiting too long. Why does Windows take so long to delete files? The time it takes Windows to prepare a file for deletion is affected by a variety of factors, including file size, storage device speed, and background processes. A long or stuck "Preparing to delete" prompt may indicate insufficient system resources, disk errors, or file system issues. exist

Can Tmp format files be deleted? Can Tmp format files be deleted? Feb 24, 2024 pm 04:33 PM

Tmp format files are a temporary file format usually generated by a computer system or program during execution. The purpose of these files is to store temporary data to help the program run properly or improve performance. Once the program execution is completed or the computer is restarted, these tmp files are often no longer necessary. Therefore, for Tmp format files, they are essentially deletable. Moreover, deleting these tmp files can free up hard disk space and ensure the normal operation of the computer. However, before deleting Tmp format files, we need to

How to install GHO files How to install GHO files Feb 19, 2024 pm 10:06 PM

The gho file is a GhostImage image file, which is usually used to back up the entire hard disk or partition data into a file. In some specific cases, we need to reinstall this gho file back to the hard drive to restore the hard drive or partition to its previous state. The following will introduce how to install the gho file. First, before installation, we need to prepare the following tools and materials: Entity gho file: Make sure you have a complete gho file, which usually has a .gho suffix and contains a backup

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. Mar 21, 2024 pm 09:17 PM

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box &quot;Error 0x80004005: Unspecified Error&quot; will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

Different uses of slashes and backslashes in file paths Different uses of slashes and backslashes in file paths Feb 26, 2024 pm 04:36 PM

A file path is a string used by the operating system to identify and locate a file or folder. In file paths, there are two common symbols separating paths, namely forward slash (/) and backslash (). These two symbols have different uses and meanings in different operating systems. The forward slash (/) is a commonly used path separator in Unix and Linux systems. On these systems, file paths start from the root directory (/) and are separated by forward slashes between each directory. For example, the path /home/user/Docume

How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? Mar 14, 2024 pm 02:07 PM

Quark Netdisk and Baidu Netdisk are currently the most commonly used Netdisk software for storing files. If you want to save the files in Quark Netdisk to Baidu Netdisk, how do you do it? In this issue, the editor has compiled the tutorial steps for transferring files from Quark Network Disk computer to Baidu Network Disk. Let’s take a look at how to operate it. How to save Quark network disk files to Baidu network disk? To transfer files from Quark Network Disk to Baidu Network Disk, you first need to download the required files from Quark Network Disk, then select the target folder in the Baidu Network Disk client and open it. Then, drag and drop the files downloaded from Quark Cloud Disk into the folder opened by the Baidu Cloud Disk client, or use the upload function to add the files to Baidu Cloud Disk. Make sure to check whether the file was successfully transferred in Baidu Cloud Disk after the upload is completed. That's it

See all articles