php+ajax实现文件切割上传功能示例

吾爱主题 阅读:143 2021-09-30 14:40:00 评论:0

本文实例讲述了php+ajax实现文件切割上传功能。分享给大家供大家参考,具体如下:

html5中的File对象继承Blob二进制对象,Blob提供了一个slice函数,可以用来切割文件数据。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 <!DOCTYPE HTML> <html lang= "zh-CN" > <head>    <meta charset= "UTF-8" >    <title></title> </head> <body>    <form method= "post" id= "myForm" >      <input type= "file" name= "file" id= "upfile" />      <input type= "submit" name= "submit" value= "提交" />    </form>    <div id= "upStatus" ></div> </body> <script type= "text/javascript" >    var myForm = document.getElementById( "myForm" );    var upfile = document.getElementById( "upfile" );      myForm.onsubmit = function () {      //获取文件对象      var file = upfile.files[0];      //获取文件大小      var fileSize = file.size;      //一次截取的大小(字节)      var CutSize = 1024 * 1024 * 10;      //开始截取位置      var CutStart = 0;      //结束截取位置      var CutEnd = CutStart + CutSize;      //截取的临时文件      var tmpfile = new Blob();        while (CutStart < fileSize) {        tmpfile = file.slice(CutStart, CutEnd);          //我们创建一个FormData对象        var fd = new FormData();        //把文件添加到FormData对象中        fd.append( "file" , tmpfile);          var xhr = new XMLHttpRequest();        //这里使用同步        xhr.open( "post" , "upfile.php" , false );          //上传进度        console.log(Math.round( (CutStart + tmpfile.size) / fileSize * 100) + "%" );          //发送FormData对象        xhr.send(fd);        //重新设置截取文件位置        CutStart = CutEnd;        CutEnd = CutStart + CutSize;      }      return false ;    }; </script> </html>

upfile.php代码如下:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?php $uploadDir = './upload/' ; if (! file_exists ( $uploadDir )) {    @ mkdir ( $uploadDir , 0777, true); } $uploadFile = $uploadDir . basename ( $_FILES [ 'file' ][ 'name' ]);   if (! file_exists ( $uploadFile )) {    //如果文件不存在    move_uploaded_file( $_FILES [ 'file' ][ 'tmp_name' ], $uploadFile ); } else {    //如果文件已存在,追加数据    file_put_contents ( $uploadFile , file_get_contents ( $_FILES [ 'file' ][ 'tmp_name' ]), FILE_APPEND); }

希望本文所述对大家PHP程序设计有所帮助。

原文链接:https://www.cnblogs.com/jkko123/p/6294581.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容