Home Web Front-end JS Tutorial FormData+Ajax implements upload progress monitoring

FormData+Ajax implements upload progress monitoring

May 22, 2018 am 09:50 AM
monitor schedule

The FormData type is actually defined at XMLHttpRequest level 2. It provides convenience for serializing tables and creating data in the same format as the form (for XHR transmission, of course). Next, I will share with you FormData Ajax to implement upload progress monitoring through this article. Friends who need it can take a look together

What is FormData?

The FormData object can assemble a set of key/value pairs used to send requests using XMLHttpRequest. It makes sending form data more flexible and convenient because it can be used independently of the form. If you set the encoding type of the form to multipart/form-data, the data format transmitted through FormData is the same as the data format transmitted by the form through the submit() method;

How to create a FormData object

You can create a FormData object yourself and then add fields by calling its append() method, like this:

//实例化一个formData对象
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("userid", 123456); // 数字 123456 会被立即转换成字符串 "123456"
// HTML上的 文件类型input[type=file]的文件框,由用户选择
formData.append("userfile", fileInputElement.files[0]);
// JavaScript file-like 对象
var content = &#39;<a id="a"><b id="b">hey!</b></a>&#39;; // 新文件的正文...
var blob = new Blob([content], { type: "text/xml"});
formData.append("webmasterfile", blob);
Copy after login

Note: The field "userfile " and "webmasterfile" both contain a file. The field "userid" is of numeric type, which will be converted to a string type by the FormData.append() method (the field type of the FormData object can be Blob, File, or string: If its If the field type is neither Blob nor File, it will be converted to a string type.

Use jQuery's Ajax method to send FormData data

//记录当前时间
var time=new Date().getTime();
//记录当前进度
var percentage =null;
//记录当前上传速度
var velocity=null;
//记录已上传文件字节大小
var loaded=0;
$.ajax({
 url: &#39;Url&#39;,
 type: "POST",
 data: formData,
 contentType: false, // 必须 不设置内容类型
 processData: false, // 必须 不处理数据
 xhr: function xhr() {
  //获取原生的xhr对象
  var xhr = $.ajaxSettings.xhr();
  if (xhr.upload) {
   //添加 progress 事件监听
   xhr.upload.addEventListener(&#39;progress&#39;, function (e) {
    var nowDate = new Date().getTime();
    //每一秒刷新一次状态
    if (nowDate - time >= 1000) {
     //已上传文件字节数/总字节数
     percentage = parseInt(e.loaded / e.total * 100);
     //当前已传大小(字节数)-一秒前已传文件大小(字节数)
     velocity = (e.loaded - loaded) / 1024;
     if (percentage >= 99) {
      $(".hintText").html(&#39;服务端正在解析,请稍后&#39;);
     } else {
      //修改上次记录时间及数据大小
      time = nowDate;
      loaded = e.loaded;
     }
    } else {
     return;
    }
   }, false);
  }
  return xhr;
 },
 success: function success(response) {
  //成功回调   
 },
 error: function error(error) {
  //失败回调    
 }
});
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

ajaxfileupload.js implements file upload (with steps Code)

php Get the headers method and content instance of ajax

ajaxfileupload. js to implement file upload (with step code)

The above is the detailed content of FormData+Ajax implements upload progress monitoring. 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
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks 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 long is home monitoring usually kept? How long is home monitoring usually kept? Aug 30, 2023 pm 04:44 PM

Home monitoring is generally kept for one to two weeks. Detailed introduction: 1. The larger the storage capacity, the longer the video can be saved; 2. The larger the capacity of the hard disk, the longer the video can be saved; 3. According to the requirements of different regions and laws and regulations, the number of surveillance videos The storage time may vary; 4. Some advanced surveillance systems can also trigger recording based on motion detection or specific events, thereby saving storage space and providing more useful recordings.

Python script for monitoring website changes Python script for monitoring website changes Aug 29, 2023 pm 12:25 PM

In today's digital age, being aware of the latest changes on your website is crucial for a variety of purposes, such as tracking updates on your competitors' websites, monitoring product availability, or staying informed of important information. Manually checking your website for changes can be time-consuming and inefficient. This is where automation comes into play. In this blog post, we will explore how to create a Python script to monitor website changes. By leveraging the power of Python and some handy libraries, we can automate the process of retrieving website content, comparing it to previous versions, and notifying us of any changes. This allows us to remain proactive and react promptly to updates or modifications to the sites we monitor. Setting up the environment Before we start writing scripts to monitor website changes, we need to set up P

How to implement request logging and monitoring in FastAPI How to implement request logging and monitoring in FastAPI Jul 30, 2023 am 08:29 AM

How to implement request logging and monitoring in FastAPI Introduction: FastAPI is a high-performance web framework based on Python3.7+. It provides many powerful functions and features, including automated request and response model verification, security, and performance optimization. wait. In actual development, we often need to record request logs in the application for debugging and monitoring analysis. This article will introduce how to implement request logging and monitoring in FastAPI and provide corresponding code examples. 1. Installation

How to open photos from surveillance camera in Windows 10 How to open photos from surveillance camera in Windows 10 Jul 10, 2023 pm 09:41 PM

If we don’t have a mobile phone at hand, only a computer, but we have to take pictures, we can use the computer’s built-in surveillance camera to take pictures, so how to turn on the win10 surveillance camera, in fact, we only need to download a camera application. The specific method to open the win10 surveillance camera. How to open photos from win10 surveillance camera: 1. First, use the disk shortcut key Win+i to open settings. 2. After opening, enter the personal privacy settings. 3. Then turn on access restrictions under camera phone permissions. 4. Once opened, you just need to open the camera application software. (If not, you can go to the Microsoft store to download one) 5. After opening, if the computer has a built-in surveillance camera or an external surveillance camera is assembled, you can take pictures. (Because people don’t have cameras installed

Real-time log monitoring and analysis under Linux Real-time log monitoring and analysis under Linux Jul 29, 2023 am 08:06 AM

Real-time log monitoring and analysis under Linux In daily system management and troubleshooting, logs are a very important data source. Through real-time monitoring and analysis of system logs, we can detect abnormal situations in time and handle them accordingly. This article will introduce how to perform real-time log monitoring and analysis under Linux, and provide corresponding code examples. 1. Real-time log monitoring Under Linux, the most commonly used log system is rsyslog. By configuring rsyslog, we can combine the logs of different applications

C# Development Advice: Logging and Monitoring Systems C# Development Advice: Logging and Monitoring Systems Nov 22, 2023 pm 08:30 PM

C# Development Suggestions: Logging and Monitoring System Summary: In the software development process, logging and monitoring systems are crucial tools. This article will introduce the role and implementation suggestions of logging and monitoring systems in C# development. Introduction: Logging and monitoring are essential tools in large-scale software development projects. They can help us understand the running status of the program in real time and quickly discover and solve problems. This article will discuss how to use logging and monitoring systems in C# development to improve software quality and development efficiency. The role of logging system

Laravel monitoring errors: improve application stability Laravel monitoring errors: improve application stability Mar 06, 2024 pm 04:48 PM

Monitoring errors in Laravel is an important part of improving application stability. During the development process, various errors will inevitably be encountered, and how to detect and resolve these errors in a timely manner is one of the keys to ensuring the normal operation of the application. Laravel provides a wealth of tools and functions to help developers monitor and handle errors. This article will introduce some of the important methods and attach specific code examples. 1. Use logging Logging is one of the important means of monitoring errors. Laravel has a powerful logging system built-in, developers

How to use Docker for container monitoring and performance analysis How to use Docker for container monitoring and performance analysis Nov 08, 2023 am 09:54 AM

Overview of how to use Docker for container monitoring and performance analysis: Docker is a popular containerization platform that allows applications to run in independent containers by isolating applications and their dependent software packages. However, as the number of containers increases, container monitoring and performance analysis become increasingly important. In this article, we will introduce how to use Docker for container monitoring and performance analysis, and provide some specific code examples. Use Docker’s own container monitoring tool Docker provides

See all articles