作为程序员一定要保持良好的睡眠,才能好编程

php处理大文件 切割与合并

发布时间:2019-04-01


开发中有时候需要php对接外部接口,明显很多的因为大小而不能一次性上传,那么就需要涉及到对文件的切割:


下面来看下如何对文件进行切割:


php版本:


分割:

$i    = 0;                               	//分割的块编号  
$fp   = fopen("hadoop.sql","rb");     	 	//要分割的文件  
$file = fopen("split_hash.txt","a");     	//记录分割的信息的文本文件,实际生产环境存在redis更合适 
while(!feof($fp)){  
        $handle = fopen("hadoop.{$i}.sql","wb");  
        fwrite($handle,fread($fp,5242880));//切割的块大小 5m
        fwrite($file,"hadoop.{$i}.sql\r\n");  
        fclose($handle);  
        unset($handle);  
        $i++;  
}  
fclose ($fp);  
fclose ($file);  
echo "ok";


合并代码

$hash = file_get_contents("split_hash.txt"); //读取分割文件的信息
$list = explode("\r\n",$hash);
$fp = fopen("hadoop2.sql","ab"); 	    //合并后的文件名
foreach($list as $value){
	if(!empty($value)) {
		$handle = fopen($value,"rb");
		fwrite($fp,fread($handle,filesize($value)));
		fclose($handle);
		unset($handle);
	}
}
fclose($fp);
echo "ok";








这里提供一个类库:

<?php

class File_split {

  public $file;

  public $cut_size = 1024;  //单位字节     2*1024*1024  2M


  public function setCutSize($size) {
    $this->cut_size = $size;
  }

  /**
   * 获取当前切割文件的大小
   * @return int
   */
  public function getCutSize() {
    return $this->cut_size;
  }

  public function cut($file) {

    $this->file = $file;
    if (!file_exists($this->file)) {
      throw new Exception($file . "文件不存在");
    }

    $cut_m = 2;
    $i = 0;
    $fp = fopen($this->file, "rb");
    $tempname = basename($this->file) . '_temp';
    while (!feof($fp)) {
      $handle = fopen("{$tempname}_{$i}.temp", "wb");
      fwrite($handle, fread($fp, $this->cut_size));
      fclose($handle);
      unset($handle);
      $i++;
    }
    fclose($fp);

    return ['file' => basename($this->file), 'temp' => $tempname];
  }

  public function merge($info) {

    if (count($info) != 2) {
      throw new Exception("传递参数不正确", 1);
    }

    $fp = fopen($info['file'], "ab");

    foreach (glob(__DIR__ . '/' . $info['temp'] . '_*.temp') as $file) {
      $handle = fopen($file, "rb");
      fwrite($fp, fread($handle, filesize($file)));
      fclose($handle);
      unset($handle);
      @unlink($file);
    }

    fclose($fp);

    return TRUE;
  }
}

//$cm = new File_split();
//$info=$cm->cut('upload.html');

$data = [
  'file' => 'uploadtest.html',
  'temp' => 'upload.html_temp'
];
$cm = new File_split();
$flag = $cm->merge($data);

var_dump($flag);