PHP大文件分块上传功能实例详解
发布:smiling 来源: PHP粉丝网 添加日期:2021-12-07 10:32:51 浏览: 评论:0
本文实例讲述了PHP大文件分块上传功能,分享给大家供大家参考,具体如下:
前端代码
使用file.slice将文件进行分割,然后分别进行异步上传。
- <!DOCTYPE html>
- <html lang="zh-cn">
- <head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title><%= title %></title>
- <!-- zui -->
- <link rel="stylesheet" href="http://zui.sexy/dist/css/zui.min.css" rel="external nofollow" >
- </head>
- <body>
- <div class="container" style="margin-top: 30px;">
- <form class="form-inline" method="post" enctype="multipart/form-data">
- <div class="form-group">
- <input type="file" id="fileBig" class="form-control">
- </div>
- <button type="submit" class="btn btn-primary">提交</button>
- </form>
- </div>
- <!-- ZUI Javascript 依赖 jQuery -->
- <script src="http://zui.sexy/assets/jquery.js"></script>
- <!-- ZUI 标准版压缩后的 JavaScript 文件 -->
- <script src="http://zui.sexy/dist/js/zui.min.js"></script>
- <script type="text/javascript">
- $('form').submit(function() {
- let file = $(":file")[0].files[0];
- let fileName = file.name;
- let fileSize = file.size;
- console.log('fileSize',fileSize);
- let blockSize = 0.9*1024*1024;
- let num = Math.ceil(fileSize/blockSize);
- let start = 0;
- let end = 0;
- for(let i=1;i<=num;i++){
- end = blockSize*i;
- if(end > fileSize){
- end = fileSize;
- }
- let block = file.slice(start,end);
- start = end;
- let fd = new FormData();
- fd.append('block',block);
- fd.append('name',fileName);
- fd.append('total',num);
- fd.append('index',i);
- $.ajax({
- url:"upload.php",
- type:"POST",
- data:fd,
- async:true,
- processData:false,
- contentType:false,
- success:(res)=>{
- console.log('res_'+i+":");
- console.log(res);
- }
- })
- }
- return false;
- });
- </script>
- </body>
- </html>
后端代码
在所有的文件上传成功之后,合并生成原来的大文件
- <?php
- $name = $_POST['name'];
- $index = $_POST['index'];
- $total = $_POST['total'];
- echo "name:".$name.PHP_EOL;
- echo "index:".$index.PHP_EOL;
- echo "total:".$total.PHP_EOL;
- move_uploaded_file($_FILES['block']['tmp_name'],'upload/'.$name."_".$index);
- $list = scandir('upload');
- $num = count($list)-2;
- echo "cur_num:".$num.PHP_EOL;
- if($num == $total){
- echo "upload done".PHP_EOL;
- echo $cmd = "cat upload/'{$name}_'* > upload/'{$name}'";
- shell_exec($cmd);
- }
Tags: PHP大文件分块上传
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)