Home Web Front-end JS Tutorial How to use ajax to implement large file upload function

How to use ajax to implement large file upload function

Mar 30, 2018 pm 05:04 PM
ajax accomplish document

This time I will show you how to use ajax to implement the function of uploading large files, and what are the precautions for using ajax to upload large files. The following is a practical case, one Get up and take a look.

Everyone knows that PHP has restrictions on uploading files. If the php.ini file has not been modified, the default upload size limit is 2M, so how to upload a large file, for example, upload a large file of more than 1G , which can be solved by cutting and uploading large files.

What is cutting and uploading large files?

Principle: Use the new features of HTML5 to cut the file content into segments of binary information, and then upload one segment to the server each time. The server only needs to integrate and store the binary information we upload each time. into a file, then the final file is the uploaded file.

Since the default upload size of php.ini is 2M, if each batch is uploaded to 2M, it will take a long time when I test. Here I limit the size to 20M, and the maximum post data is 28M, which is convenient for testing. . If its parameters cannot be modified during actual development, the data uploaded in each batch cannot exceed the maximum limit.

post_max_size = 28M 
upload_max_filesize = 20M
Copy after login

I uploaded it in nginx, so I still need to modify the NginxConfiguration file/etc/nginx/nginx.con

//在http{} 里面加即可 
client_max_body_size 50m   #客户端最大上传大小 50M
Copy after login

File object in JavaScript

We have already used this API in the previous article. The File object stores the size, name, type and other information of the file

Blob object in JavaScript

The Blob object is a binary object and is also the parent class of the File object. There is a very important method in the Blob object: the slice() method. Using this method, we can cut the file content into binary information. The slice() method accepts three parameters, a starting offset, an ending offset, and an optional mime type. If the mime type is not set, the new Blob object has the same mime type as the parent.

Upload page index.php:

<!DOCTYPE html> 
<html> 
<head> 
  <meta charset="utf-8"> 
  <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
  <title>大文件切割上传</title> 
  <link rel="stylesheet" href=""> 
  <script> 
    function selfile(){ 
      const LENGTH = 1024 * 1024 * 10;//每次上传的大小 
      var file = document.getElementsByName('video')[0].files[0];//文件对象 
      var filename=document.getElementsByName('video')[0].files[0].name; 
      var totalSize = file.size;//文件总大小 
      var start = 0;//每次上传的开始字节 
      var end = start + LENGTH;//每次上传的结尾字节 
      var fd = null//创建表单数据对象 
      var blob = null;//二进制对象 
      var xhr = null;//xhr对象 
      while(start < totalSize){ 
        fd = new FormData();//每一次需要重新创建 
        xhr = new XMLHttpRequest();//需要每次创建并设置参数 
        xhr.open(&#39;POST&#39;,&#39;upload.php&#39;,false); 
        blob = file.slice(start,end);//根据长度截取每次需要上传的数据 
        fd.append(&#39;video&#39;,blob);//添加数据到fd对象中 
        fd.append(&#39;filename&#39;,filename); //获取文件的名称 
        xhr.send(fd);//将fd数据上传 
 
        //重新设置开始和结尾 
        start = end; 
        end = start + LENGTH; 
 
      } 
 
    } 
  </script> 
</head> 
<body> 
<h1>大文件切割上传</h1> 
<input type="file" name="video" onchange="selfile();" /> 
</body> 
</html>
Copy after login

Receive data page upload.php:

<?php 
/** 
 * 大文件切割上传,把每次上传的数据合并成一个文件 
 */ 
 
$filename = &#39;./uploads/&#39;.$_POST[&#39;filename&#39;];//确定上传的文件名 
//第一次上传时没有文件,就创建文件,此后上传只需要把数据追加到此文件中 
if(!file_exists($filename)){ 
 move_uploaded_file($_FILES[&#39;video&#39;][&#39;tmp_name&#39;],$filename); 
}else{ 
 file_put_contents($filename,file_get_contents($_FILES[&#39;video&#39;][&#39;tmp_name&#39;]),FILE_APPEND); 
} 
?>
Copy after login

Before testing, create the uploads folder first

If it is linux For the system, remember to give permission to uploads

sudo chmod -R 777 uoloads/  //赋予uploads文件夹 777 权限  -R 递归子文件
Copy after login

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 to use Ajax to asynchronously check whether the user name is duplicated

ajax should get json data as undefined how to use

The above is the detailed content of How to use ajax to implement large file upload function. 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)

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

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

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

What is hiberfil.sys file? Can hiberfil.sys be deleted? What is hiberfil.sys file? Can hiberfil.sys be deleted? Mar 15, 2024 am 09:49 AM

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

Detailed explanation of the role of .ibd files in MySQL and related precautions Detailed explanation of the role of .ibd files in MySQL and related precautions Mar 15, 2024 am 08:00 AM

Detailed explanation of the role of .ibd files in MySQL and related precautions MySQL is a popular relational database management system, and the data in the database is stored in different files. Among them, the .ibd file is a data file in the InnoDB storage engine, used to store data and indexes in tables. This article will provide a detailed analysis of the role of the .ibd file in MySQL and provide relevant code examples to help readers better understand. 1. The role of .ibd files: storing data: .ibd files are InnoDB storage

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

See all articles