php 分片,PHP大文件分割上传 PHP分片上传

服务端为什么不能直接传大文件?跟php.ini里面的几个配置有关upload_max_filesize = 2M //PHP最大能接受的文件大小post_max_size = 8M //PHP能收到的最大POST值"memory_limit = 128M //内存上限max_execution_time = 30 //最大执行时间

当然不能简单粗暴的把上面几个值调大,否则服务器内存资源吃光是迟早的问题。

解决思路

好在HTML5开放了新的FILE API,也可以直接操作二进制对象,我们可以直接在浏览器端实现文件切割,按照以前的做法就得用Flash的方案,实现起来会麻烦很多。

JS思路1.监听上传按钮的onchange事件2.获取文件的FILE对象3.把文件的FILE对象进行切割,并且附加到FORMDATA对象中4.把FORMDATA对象通过AJAX发送到服务器5.重复3、4步骤,直到文件发送完。

PHP思路1.建立上传文件夹2.把文件从上传临时目录移动到上传文件夹3.所有的文件块上传完成后,进行文件合成4.删除文件夹5.返回上传后的文件路径

DEMO代码

前端部分代码

Document

PHP部分代码<?phpclass Upload{ private $filepath = "./upload"; //上传目录 private $tmpPath; //PHP文件临时目录 private $blobNum; //第几个文件块 private $totalBlobNum; //文件块总数 private $fileName; //文件名 public function __construct($tmpPath,$blobNum,$totalBlobNum,$fileName){ $this->tmpPath = $tmpPath; $this->blobNum = $blobNum; $this->totalBlobNum = $totalBlobNum; $this->fileName = $fileName; $this->moveFile(); $this->fileMerge(); } //判断是否是最后一块,如果是则进行文件合成并且删除文件块 private function fileMerge(){ if($this->blobNum == $this->totalBlobNum){ $blob = ""; for($i=1; $i<= $this->totalBlobNum; $i++){ $blob .= file_get_contents($this->filepath."/". $this->fileName."__".$i); } file_put_contents($this->filepath."/". $this->fileName,$blob); $this->deleteFileBlob(); } } //删除文件块 private function deleteFileBlob(){ for($i=1; $i<= $this->totalBlobNum; $i++){ @unlink($this->filepath."/". $this->fileName."__".$i); } } //移动文件 private function moveFile(){ $this->touchDir(); $filename = $this->filepath."/". $this->fileName."__".$this->blobNum; move_uploaded_file($this->tmpPath,$filename); } //API返回数据 public function apiReturn(){ if($this->blobNum == $this->totalBlobNum){ if(file_exists($this->filepath."/". $this->fileName)){ $data["code"] = 2; $data["msg"] = "success"; $data["file_path"] = "http://".$_SERVER["HTTP_HOST"].dirname($_SERVER["DOCUMENT_URI"]).str_replace(".","",$this->filepath)."/". $this->fileName; } }else{ if(file_exists($this->filepath."/". $this->fileName."__".$this->blobNum)){ $data["code"] = 1; $data["msg"] = "waiting for all"; $data["file_path"] = ""; } } header("Content-type: application/json"); echo json_encode($data); } //建立上传文件夹 private function touchDir(){ if(!file_exists($this->filepath)){ return mkdir($this->filepath); } }}//实例化并获取系统变量传参$upload = new Upload($_FILES["file"]["tmp_name"],$_POST["blob_num"],$_POST["total_blob_num"],$_POST["file_name"]);//调用方法,返回结果$upload->apiReturn();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持网页设计。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值