Home Web Front-end Layui Tutorial Introduction to uploading large files using tp5+layui

Introduction to uploading large files using tp5+layui

Dec 16, 2019 pm 05:28 PM
layui

Introduction to uploading large files using tp5+layui

First record some configuration information to change the file upload size.

Open php.ini

file_uploads = ON // Whether to allow the switch to upload files through http, and turn on the path of

# UPLOAD_TMP_DIR // Temporary files

UPLOAD_MAX_FILESIZE 20M // The maximum value of the file to be uploaded

#post_max_size 22M //The size that can be uploaded through form POST

max_execution_time 600 //The maximum time a single PHP page is allowed to run

max_input_time 600 //The maximum time required for a single PHP page to receive data Time, default is 60 seconds

memory_limit 256M //The maximum memory that can be occupied during the execution of a single PHP page, the default is 8M

You can adjust the allowed file upload by changing the above configuration size. (Some also need to adjust some server configurations)

Supplement: 413 error If the server is nginx, you need to change the client_max_body_size 24M in the configuration nginx_conf and set the maximum value for receiving packets sent by the client. Remember to put it in http, restart the server, use restart, don't use reload.

Then start to realize the split upload of files.

File Select the file to upload through the file of the HTML input tag. Through H5 new object FileReader. Just like the literal meaning, the FileRaeder object is an object that reads local files. The FileReader object can read local files and return them in base64 encoding. (For specific information on the use of FileReader objects, please refer to Baidu, or read the following blog post, which is very specific.

Actual development

First attempt

Select the file through the input file tag

Use the FileReader object to read the file

Send the base64 encoding of the file to the server asynchronously through ajax

The server receives The encoding is then decoded and saved to the file.

The test result fails. When the file is too large, the length of the encoding is also longer. The maximum online parameter submission through asynchronous ajax is 8000 bytes.

Second attempt

Split and upload the obtained base64 encoding based on the first attempt

Divide the obtained base64 encoded string into several parts and perform Number, call ajax in a loop to send

After receiving the data, the server will decode the data and name it with the number

After receiving all the small files, call the background method to merge the small files

The test result failed. When the uploaded file exceeded 1G, the browser crashed. It should be that when reading the file, the file was too large, and the base64 encoding returned by the one-time read was too large, causing the page to crash.

Third attempt

Based on the second attempt, I also thought of reading in batches during the process of reading files to obtain encodings to avoid page crashes caused by reading too large files at once. .

Here we need to use H5's file.slice() to divide the file into chunks, so as to achieve batch reading and batch uploading.

Read the file through the FlieReader object Kuai

Asynchronously send the base64 encoding to the server through ajax

The server receives the data for decoding and file saving

The test was successful and the test uploaded a 4G file.

(Because the file is segmented, a large number of ajax requests will be initiated when uploading large files, resulting in a large amount of concurrency, which may cause the page to crash again. That’s why I used staggered requests. Slow down The speed of generating ajax requests.)

Specific implementation code

Next post some code

Front-end framework: layui

Back-end framework: tp5

Page code:

<div class="layui-form-item">
    <label class="layui-form-label">视频上传</label>
    <div class="layui-input-block layui-upload-video-btn">
        <ul>
            <li class="img-upload">
                <label></label>
                <input type="file" class="video-upload-file layui-upload-video-file-btn" name="file"/>
                <video width="320" height="240" controls style="display: none">
                    <source src="" type="video/mp4">
                    <source src="" type="video/ogg">
                    您的浏览器不支持Video标签。
                </video>
                <span style="display: none">X</span>
                <input type="hidden" class="video-link-id" name="video_link_id" value="">
            </li>
            <li>//视频上传会比较久(上传完会有提示)</li>
        </ul>
    </div>
</div>
Copy after login

js code:

$(&#39;.video-upload-file&#39;).on(&#39;change&#39;,function(){
        layer.msg(&#39;正在提交视频......&#39;);
        //隐藏按钮,显示进度条
        $(&#39;.layui-upload-video&#39;).hide();
        $(&#39;.layui-progress-ads&#39;).show();
        var loads_video = layer.load(2,{shade: [0.2, &#39;#3a3535&#39;]});      //产生加载圈,禁止用户其他操作
        var thisFile = $(this);
        var reader=new FileReader();
        var file_size = this.files[0].size;     //文件大小
        var limit = 8388608;        //每次读取文件的大小
        // var limit = 1048000;        //每次读取文件的大小
        var up_count = Math.ceil(file_size/limit);     //总上传次数
        var type = this.files[0].type.substr(this.files[0].type.indexOf(&#39;/&#39;)+1);   //文件类型
        var success_num = 0;        //用于存放上传成功的数据的id
        var check = 1;             //防止多次合并
        console.log(&#39;文件大小:&#39;+this.files[0].size);
        console.log(&#39;文件类型:&#39;+type);
        console.log(&#39;分割上传次数:&#39;+up_count);
        //分段读取文件
        readFile(this.files[0], 0, limit);
        function readFile(file, num, limit){
            // console.log(&#39;第&#39;+num+&#39;次:&#39;+num*limit);
            reader.readAsDataURL(file.slice(num*limit, (num+1)*limit));
            reader.onload = function(e){
                console.log(reader.result.length);
                console.log(reader.result);
                //异步base64的数据传输到服务器
                ajax_way(reader.result, name, num+1, thisFile);
                if((num+1)*limit <= file_size){
                    readFile(file, num+1, limit);
                }
            }
        }
        function ajax_way(data,name,num, thisFile){
            //避免一次性生成太多的请求
            if(num+1 > 60){
                // console.log(&#39;等待两秒&#39;);
                sleep(6000);
                // console.log(&#39;等待结束&#39;);
            }
            $.ajax({
                url: "<?= url(&#39;admin/video/up_mfile&#39;);?>",
                type: "POST",
                data: {video:data,name:name,num:num},
                // async:false,      //是否采用同步,串行发送请求
                success: function (data) {
                    if(data.code == 1){
                        //上传成功,成功次数加一
                        success_num++;
                        console.log(num+&#39;完成&#39;);
                        console.log(&#39;已完成:&#39;+success_num+&#39;/&#39;+up_count);
                        //计算完成的百分比
                        var precentage = Math.ceil((success_num/up_count)*100);
                        //更改进度条显示
                        $(&#39;.layui-progress-ads-btn&#39;).attr(&#39;lay-percent&#39;, precentage+&#39;%&#39;);
                        $(&#39;.layui-progress-ads-btn&#39;).css(&#39;width&#39;, precentage+&#39;%&#39;);
                        $(&#39;.layui-progress-text&#39;).html(precentage+&#39;%&#39;);
                        //如果分割文件都上传了则调用接口合并文件
                        if(success_num == up_count && check == 1){
                            check = 0;
                            success_num = 0;
                            merge_mfile(name, up_count, thisFile, type);
                        }
                    }
                },
                error:function(e){
                    console.log(&#39;出错了:&#39;+num);
                    //传输出错则重新上传
                    ajax_way(data, name, num, thisFile);
                }
            });
        }

        //合并文件
        function merge_mfile(name, count, thisFile, type){
            $.ajax({
                url:"<?= url(&#39;admin/video/merge_mfile&#39;);?>",
                data:{name:name, count:count, type:type},
                type:"POST",
                success:function(data){
                    if (data.code==1){
                        layer.close(loads_video);
                        layer.msg(&#39;视频提交成功&#39;);
                        thisFile.siblings(&#39;.video-link-id&#39;).val(data.data);
                    }else{
                        layer.msg(&#39;视频提交异常请重新提交&#39;);
                        //显示按钮,隐藏进度条
                        $(&#39;.layui-upload-video&#39;).show();
                        $(&#39;.layui-progress-ads&#39;).hide();
                        //将进度条置零
                        $(&#39;.layui-progress-ads-btn&#39;).attr(&#39;lay-percent&#39;, &#39;0%&#39;);
                        $(&#39;.layui-progress-ads-btn&#39;).css(&#39;width&#39;, &#39;0%&#39;);
                        $(&#39;.layui-progress-text&#39;).html(&#39;0%&#39;);
                        //清空已选中的文件
                        var file = $(".layui-upload-video-file-btn");
                        file.after(file.clone().val(""));
                        file.remove();
                    }
                }
            })
        }
        function sleep(n) { //n表示的毫秒数
            var start = new Date().getTime();
            while (true) if (new Date().getTime() - start > n) break;
        }
        return false;
    });
Copy after login

For more layui knowledge, please pay attention to the layui usage tutorial column.

The above is the detailed content of Introduction to uploading large files using tp5+layui. 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 to set up jump on layui login page How to set up jump on layui login page Apr 04, 2024 am 03:12 AM

Layui login page jump setting steps: Add jump code: Add judgment in the login form submit button click event, and jump to the specified page through window.location.href after successful login. Modify the form configuration: add a hidden input field to the form element of lay-filter="login", with the name "redirect" and the value being the target page address.

How to get form data in layui How to get form data in layui Apr 04, 2024 am 03:39 AM

layui provides a variety of methods for obtaining form data, including directly obtaining all field data of the form, obtaining the value of a single form element, using the formAPI.getVal() method to obtain the specified field value, serializing the form data and using it as an AJAX request parameter, and listening Form submission event gets data.

How layui implements self-adaptation How layui implements self-adaptation Apr 26, 2024 am 03:00 AM

Adaptive layout can be achieved by using the responsive layout function of the layui framework. The steps include: referencing the layui framework. Define an adaptive layout container and set the layui-container class. Use responsive breakpoints (xs/sm/md/lg) to hide elements under specific breakpoints. Specify element width using the grid system (layui-col-). Create spacing via offset (layui-offset-). Use responsive utilities (layui-invisible/show/block/inline) to control the visibility of elements and how they appear.

How to transfer data in layui How to transfer data in layui Apr 26, 2024 am 03:39 AM

The method of using layui to transmit data is as follows: Use Ajax: Create the request object, set the request parameters (URL, method, data), and process the response. Use built-in methods: Simplify data transfer using built-in methods such as $.post, $.get, $.postJSON, or $.getJSON.

What is the difference between layui and vue? What is the difference between layui and vue? Apr 04, 2024 am 03:54 AM

The difference between layui and Vue is mainly reflected in functions and concerns. Layui focuses on rapid development of UI elements and provides prefabricated components to simplify page construction; Vue is a full-stack framework that focuses on data binding, component development and state management, and is more suitable for building complex applications. Layui is easy to learn and suitable for quickly building pages; Vue has a steep learning curve but helps build scalable and easy-to-maintain applications. Depending on the project needs and developer skill level, the appropriate framework can be selected.

How to run layui How to run layui Apr 04, 2024 am 03:42 AM

To run layui, perform the following steps: 1. Import layui script; 2. Initialize layui; 3. Use layui components; 4. Import layui styles (optional); 5. Ensure script compatibility and pay attention to other considerations. With these steps, you can build web applications using the power of layui.

What does layui mean? What does layui mean? Apr 04, 2024 am 04:33 AM

layui is a front-end UI framework that provides a wealth of UI components, tools and functions to help developers quickly build modern, responsive and interactive web applications. Its features include: flexible and lightweight, modular design, rich components, Powerful tools and easy customization. It is widely used in the development of various web applications, including management systems, e-commerce platforms, content management systems, social networks and mobile applications.

What language is layui framework? What language is layui framework? Apr 04, 2024 am 04:39 AM

The layui framework is a JavaScript-based front-end framework that provides a set of easy-to-use UI components and tools to help developers quickly build responsive web applications. Its features include: modular, lightweight, responsive, and has complete documentation and community support. layui is widely used in the development of management backend systems, e-commerce websites, and mobile applications. The advantages are quick start-up, improved efficiency, and easy maintenance. The disadvantages are poor customization and slow technology updates.

See all articles