上传大文件之分包操作-js处理

当一个文件足够大的时候,通常上传会有两个问题,1:上传大小限制。2:上传速度太慢。

这个时候我们可以考虑分包上传。即是:将一个大文件 分成足够多的小文件分别上传。

 php后端1:上传类

<?php

namespace App\Support;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadSupport {

    // 文件
    protected $file;
    // 文件名字
    protected $fileName;
    // 文件大小
    protected $fileSize;
    // 文件后缀名
    protected $fileExtension;
    // 图片允许后缀名
    protected $imagesExtension = ['png','jpeg','jpg','gif'];
    // 文件允许后缀名
    protected $docExtension = ['docx','doc','csv','pdf','xls','xlsx'];
    // 存储文件夹
    protected $url = 'default';
    // 存储路径
    protected $pathUrl = '';
    /**
     * 参数实例化
     */
    public function requestFile(Request $request){
        $this->file = $request->file('part');
        $this->fileName = $request->input('name');
        $this->filesize = $this->file->getSize();
        $this->fileExtension = $this->file->extension();
        return $this;
    }
    /**
     * 判断文件存储路径
     */
    public function pathCheck(){
        if(in_array($this->fileExtension,$this->imagesExtension)){
            $this->path = 'images';
        }
        if(in_array($this->fileExtension,$this->docExtension)){
            $this->path = 'doc';
        }
        $this->existDir();
        $this->pathUrl = Storage::path('local').'\\'.$this->url.'\\'.$this->fileName;
        return $this;
    }
    /**
     * 判断路径是否存在,不存在则创建
     */
    public function existDir(){
        if(!is_dir(Storage::path('local').'\\'.$this->url)){
            mkdir(Storage::path('local').'\\'.$this->url);
        }

        return true;
    }
    /**
     * 上传文件
     */
    public function uploadFile(){
        if(!file_exists($this->pathUrl)){
            return move_uploaded_file($this->file->path(),$this->pathUrl);
        }
        return file_put_contents($this->pathUrl,file_get_contents($this->file->path()),FILE_APPEND);

    }
}

php调用:controller

public function upload(Request $request,UploadSupport $uploadSupport){
        $upload = $uploadSupport->requestFile($request);
        $upload->pathCheck()->uploadFile();

        return response()->json([
            'code' => 200,
            'info' => '上传成功'
        ]);
    }

注意要去掉上传表单提交的crsf验证。

前端:

    <script src="/js/jquery.min.js"></script>
    <title>Ajax上传文件进度条显示</title>
    <script type="text/javascript">
        function sendfile(){
            const LENGTH=10*1024*1024;
            var sta=0;
            var end=sta+LENGTH;
            var blob=new Blob();
            var fd=null;

            var xhr=null;

            var pic=document.getElementById('upfile').files[0];
            console.log(pic);
            var name= pic.name;
            var  totalsize=pic.size;

            var precent=null;
            while(sta<totalsize){
                blob=pic.slice(sta,end);
                var formData = new FormData();
                formData.append("part", blob);
                formData.append("name", name);
                $.ajax({
                    url: '{{route("upload")}}',
                    type: 'POST',
                    cache: false,
                    data: formData,
                    async: false,
                    processData: false,
                    contentType: false,
                }).done(function(res){ 
                   precent=100 * (end/totalsize);
                    if(precent>100){
                        precent=100;
                    }
                    console.log(Math.round(precent)+'%');
                    $('#precent').html(Math.floor(precent)+'%');
                }).fail(function(res) {
                });
         
// xhr=new XMLHttpRequest(); // xhr.open('POST','{{route("upload")}}',false); // fd=new FormData(); // fd.append('part',blob); // fd.append('name',name); // xhr.send(fd); // xhr.upload.onprogress = progressFunction; // var response = JSON.parse(xhr.responseText); // if (response.code == 422){ // alert(response.error); // break; // } // precent=100 * (end/totalsize); // if(precent>100){ // precent=100; // } // console.log(Math.round(precent)+'%'); // document.getElementById('precent').innerHTML=Math.floor(precent)+'%'; sta=end; end=end+LENGTH; } } </script> </head> <body> <input type="file" name="upfile" id="upfile"> <button type="button" onclick="sendfile();">上传</button> <span id="precent" class="precent"></span> </body> </html>

 

posted @ 2021-10-08 13:51  wish_yang  阅读(647)  评论(0编辑  收藏  举报