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

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

Apr 03, 2018 pm 03:00 PM
upload several kinds

This time I will bring you ajax+html implementationFile uploadWhat are the methods, what are the notesof ajax+html implementation file, the following is a practical case, one Get up and 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, but the element that really 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 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!

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:

How does ajax submit a form and implement file upload


Ajax transmits json format data to the background. How to handle errors

The above is the detailed content of What are the methods to 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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 implement file upload and processing in FastAPI How to implement file upload and processing in FastAPI Jul 28, 2023 pm 03:01 PM

How to implement file upload and processing in FastAPI FastAPI is a modern, high-performance web framework that is easy to use and powerful. It provides native support for file upload and processing. In this article, we will learn how to implement file upload and processing functions in the FastAPI framework, and provide code examples to illustrate specific implementation steps. First, we need to import the required libraries and modules: fromfastapiimportFastAPI,UploadF

Simple steps to upload your own music on Kugou Simple steps to upload your own music on Kugou Mar 25, 2024 pm 10:56 PM

1. Open Kugou Music and click on your profile picture. 2. Click the settings icon in the upper right corner. 3. Click [Upload Music Works]. 4. Click [Upload Works]. 5. Select the song and click [Next]. 6. Finally, click [Upload].

How to upload lyrics to QQ Music How to upload lyrics to QQ Music Feb 23, 2024 pm 11:45 PM

With the advent of the digital age, music platforms have become one of the main ways for people to obtain music. However, sometimes when we listen to songs, we find that there are no lyrics, which is very disturbing. Many people hope that lyrics can be displayed when listening to songs to better understand the content and emotions of the songs. QQ Music, as one of the largest music platforms in China, also provides users with the function of uploading lyrics, so that users can better enjoy music and feel the connotation of the songs. The following will introduce how to upload lyrics on QQ Music. first

How to solve the problem of slow upload speed on Win10 computer How to solve the problem of slow upload speed on Win10 computer Jul 01, 2023 am 11:25 AM

How to solve the slow upload speed of Win10 computer? When we use the computer, we may feel that the file upload speed of our computer is very slow. So what is the situation? In fact, this is because the default upload speed of the computer is 20%, so the upload speed is very slow. Many friends do not know how to operate in detail. The editor has compiled the steps to format the C drive in Win11 below. If you are interested, follow Let’s take a look below! Solution to the slow upload speed of Win10 1. Press win+R to call up run, enter gpedit.msc, and press Enter. 2. Select the management template, click Network--Qos Packet Scheduler, and double-click Limit to reserve bandwidth. 3. Select Enabled, which will bring

How to improve computer upload speed How to improve computer upload speed Jan 15, 2024 pm 06:51 PM

Upload speed becomes very slow? I believe this is a problem that many friends will encounter when uploading things on their computers. If the network is unstable when using a computer to transfer files, the upload speed will be very slow. So how can I increase the network upload speed? Below, the editor will tell you how to solve the problem of slow computer upload speed. When it comes to network speed, we all know that the speed of opening web pages, download speed, and upload speed are also very critical. Especially some users often need to upload files to the network disk, so a fast upload speed will undoubtedly save you a lot of money. Less time, what should I do if the upload speed is slow? Below, the editor brings you pictures and texts on how to deal with slow computer upload speeds. How to solve the problem of slow computer upload speed? Click "Start--Run" or "Window key"

How to take photos and upload them on computer How to take photos and upload them on computer Jan 16, 2024 am 10:45 AM

As long as the computer is equipped with a camera, it can take pictures, but some users still don't know how to take pictures and upload them. Now I will give you a detailed introduction to the method of taking pictures on the computer, so that users can upload the pictures wherever they want. How to take photos and upload them on a computer 1. Mac computer 1. Open Finder and click the application on the left. 2. After opening, click the Camera application. 3. Just click the photo button below. 2. Windows computer 1. Open the search box below and enter camera. 2. Then open the searched application. 3. Click the photo button next to it.

How to implement video playback and upload functions through the PHP Kuaishou API interface How to implement video playback and upload functions through the PHP Kuaishou API interface Jul 21, 2023 pm 04:37 PM

How to implement video playback and upload functions through the PHP Kuaishou API interface. Introduction: With the rise of social media, the public’s demand for video content has gradually increased. Kuaishou, as a short video-themed social application, is loved by many users. This article will introduce how to use PHP to write code to implement video playback and upload functions through the Kuaishou API interface. 1. Obtain the access token. Before using the Kuaishou API interface, you first need to obtain the access token. Token is the identity for accessing the API interface

How to implement avatar upload function in Vue How to implement avatar upload function in Vue Nov 07, 2023 am 08:01 AM

Vue is a popular front-end framework that can be used to build highly interactive applications. During the development process, uploading avatars is one of the common requirements. Therefore, in this article, we will introduce how to implement the avatar upload function in Vue and provide specific code examples. Using a third-party library In order to implement the avatar upload function, we can use a third-party library, such as vue-upload-component. This library provides an upload component that can be easily integrated into Vue applications. Here is a simple example

See all articles