PHP(thinkphp6)大文件分片上传到服务器

    //分片上传
    public function shardingUploadFile()
    {
        if ($this->request->isGet()) {
            $code = md5(uniqid()); // 文件的唯一编码
            return $this->fail('文件唯一码', ['code' => $code]);
        } elseif ($this->request->isPost()) {
            try {
                $file = $this->request->file('file');  //文件
                $code = $this->request->post('code', ''); //唯一码
                $sort = $this->request->post('sort', ''); //片数
                $tag = $this->request->post('tag', '');   //默认2, 1是最后一片
                $ext = $this->request->post('ext', '');   //文件后缀

                if ($file && $code && $sort && $tag) {
                    $dir = '../public/upload/' . $code;
                    if (!file_exists($dir)) mkdir($dir, 0777, true);
                    if (!file_exists($dir . '/' . $sort . '.'.$ext)) {
                        $file->move($dir . '/', $sort . '.'.$ext);
                    }
                    if ($tag == 1 && $ext) {
                        $save_file = '../public/upload/'. date('Ymd') .'/';
                        if(!file_exists($save_file)){
                            mkdir($save_file, 0777, true);
                        }
                        $file_name = $code . '.' . $ext;
                        for ($i = 1; $i <= $sort; $i++) {
                            $str = file_get_contents($dir . '/' . $i . '.'.$ext);
                            file_put_contents($save_file . $file_name, $str, FILE_APPEND);

//                            $fileHandle = fopen($save_file . $file_name, 'a');
//                            fwrite($fileHandle, $str);

                            unlink($dir . '/' . $i . '.'.$ext);
                        }
    //                        fclose($fileHandle);


                        rmdir($dir);
                        $file_url = env('IMAGE_URL.DNS') . '/upload/' . date('Ymd') .'/'. $file_name;
                        $file_size = filesize($save_file . $file_name);
                        return $this->success('分片上传成功', ['file_url' => $file_url, 'file_size' => $file_size]);
                    }
                    return $this->success('上传成功', );
                }

                return $this->fail('上传类型错误');
            } catch (\Exception $e) {
                return $this->fail($e->getMessage());
            }
        }
        return $this->fail('请求方式错误');
    }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值