存储每一块数据PHP



您好,我正在尝试将数据上传到我的服务器,但我的要求是,如果上传的内容是一个大文件,并且如果连接断开连接,我们需要上传相同的文件从它停止的地方并且不要重新启动。我可以正常将文件上传到服务器,但无法继续上传。还有其他方法可以做到这一点吗?以下是我的代码。

恢复。.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>

我可以让代码在本地主机上工作,但我在服务器上使用它时遇到问题,因为我的数据没有分块并保存在服务器上

你需要用jQuery将文件读入字符串,将该字符串切成几块,然后分别上传每个片段。

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

最新更新