Created
April 21, 2020 17:13
-
-
Save apurbajnu/694bf4c6584be0892b27fec3878feec2 to your computer and use it in GitHub Desktop.
Upload big file in chunk with ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (isset($_FILES['upload'])) { | |
$target_path = __DIR__.'/upload/'; | |
$tmp_name = $_FILES['upload']['tmp_name']; | |
$filename = $_FILES['upload']['name']; | |
$size = $_FILES['upload']['size']; | |
$target_file = $target_path.$filename; | |
//$num = isset($_POST['num'])?$_POST['num']:1; | |
$num = $_POST['num']; | |
uploadBigFile( $tmp_name, $num, $target_file, $_POST['size']); | |
} | |
/** | |
* @param $tmp_file temporary file //tmp_name | |
* @param int $current_file_size // how much bite uploaded till now | |
* @param $target_file_path // where to save the file | |
* @param $file_size // file actual size | |
*/ | |
function uploadBigFile($tmp_file,$current_file_size=0,$target_file_path,$file_size){ | |
header('content-type:application/json'); | |
if (!is_dir('upload')) { | |
mkdir('upload'); | |
} | |
$count = 0; | |
while ($current_file_size != 0 && !file_exists($target_file_path)) { | |
$count++; | |
if ($count > 20) { | |
// after 1 seconds | |
echo json_encode(array('status' => false)); | |
exit; | |
} | |
usleep(50000); | |
} | |
if ($current_file_size == 0) { | |
$desc = fopen($target_file_path, 'c'); | |
// you may decide the max size | |
ftruncate($desc, $file_size); | |
} else { | |
for ($count = 0;; $count++) { | |
if (filesize($target_file_path) == 0) { | |
if ($count > 20) { | |
// after 1 seconds | |
echo json_encode(array('status' => false)); | |
exit; | |
} | |
usleep(50000); | |
clearstatcache(false, $target_file_path); | |
} else { | |
$desc = fopen($target_file_path, 'r+'); | |
break; | |
} | |
} | |
} | |
fseek($desc, $current_file_size); | |
$src = fopen($tmp_file, 'r'); | |
while (!feof($src)) { | |
$buf = fread($src, 2097152); //4M | |
fwrite($desc, $buf); | |
} | |
fclose($src); | |
fclose($desc); | |
//echo json_encode(array('status' => true, 'block' => $_POST['block'])); | |
die(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment