存储每一块数据php

时间:2014-11-27 08:39:02

标签: php file-upload chunking large-file-upload

您好我正在尝试将数据上传到我的服务器,但我的要求是上传的内容是一个大文件,如果连接断开,我们需要从停止的位置上传相同的文件,而不是重新开始。我可以将我的文件正常上传到服务器,但我无法恢复上传..有没有其他方法可以做到这一点?以下是我的代码。

RESUME.PHP



    <?php

    $host = "localhost";
    $db_uname = "root";
    $db_pass="";
    $db_name = "upload";
    $cont=mysql_pconnect($host,$db_uname,$db_pass) or die("Too many connection, please try later ");
mysql_select_db($db_name);
 
    ob_clean();
    if($_POST['submit'])
    {

     define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of tiles chunk

    // Read a file and display its content chunk by chunk
      function readfile_chunked($filename, $retbytes = TRUE) {
    	mysql_query("INSERT INTO uploads(chunk) VALUES('')") or die('insert query: ' . mysql_error());

	$last = mysql_insert_id();
	$file = '/tmp/'.$_FILES['file']['name']; // file where it is saved after chunking
	$buffer = '';
    $cnt =0;
   
    $handle = fopen($filename, 'rb');
	$a=file_get_contents($filename);
	
	$sql=mysql_fetch_array(mysql_query("select chunk from uploads where id='26'"));
	$b= $sql['chunk'];
	
	if(strcmp($a,$b)==0) // to check if file chunked in folder                               and database data are same
	{
	echo "success";
	
	}
	else
	{
	echo "failure";
	
	}
	//exit;
    if ($handle === false) {
      return false;
    }
    while (!feof($handle)) {
      $buffer = fread($handle, CHUNK_SIZE);
   
    // Open the file to get existing content
    $current = file_get_contents($file);
    // Append a new person to the file
     $current .= $buffer;
    // Write the contents back to the file
    file_put_contents($file, $current);
    mysql_query("update uploads set chunk =concat(chunk,'".mysql_real_escape_string($buffer)."') where id='$last'") or die('update query: ' . mysql_error());
        ob_flush();
      flush();
	 
      if ($retbytes) {
        $cnt += strlen($buffer);
		//echo $cnt;
      }
	 
    }
	
    $status = fclose($handle);
    if ($retbytes && $status) {
	//echo $cnt;
      return $cnt; // return num. bytes delivered like                               readfile() does.
    }
    return $status;
  }


  
    $filename = $_FILES['file']['tmp_name'];
    readfile_chunked($filename);
 }
?>

<form action="resume.php" method="post"
                        enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit"  name="submit" value="Upload File" />
</form>
&#13;
&#13;
&#13;

我可以让代码在localhost上运行,但我在服务器上使用它时遇到问题,因为我的数据没有分块并保存在服务器上

2 个答案:

答案 0 :(得分:0)

您需要使用jQuery将文件读入字符串,将该字符串剪切成碎片,然后单独上传每个部分。

答案 1 :(得分:0)

你可以试试这个“resumablejs”http://resumablejs.com/,它会创建数据块并将其发送到服务器端,从服务器端你可以从接收到的块创建原始文件。