Skip to content

Commit e8fbd44

Browse files
fix: combine the chunks
1 parent 2af426c commit e8fbd44

File tree

1 file changed

+42
-2
lines changed

1 file changed

+42
-2
lines changed

inc/files.php

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,9 +205,11 @@ function ppom_upload_file() {
205205
$file_path_thumb = $file_dir_path . 'thumbs';
206206
$file_name = wp_unique_filename( $file_path_thumb, $file_name );
207207
$file_name = strtolower( $file_name );
208+
$original_name = $file_name;
208209
$file_ext = pathinfo( $file_name, PATHINFO_EXTENSION );
210+
$original_name = str_replace(".$file_ext", "", $original_name);
209211
$unique_hash = substr( hash( 'sha256', wp_generate_password( 8, false, false ) ), 0, 8 );
210-
$file_name = str_replace( ".$file_ext", ".$unique_hash.$file_ext", $file_name );
212+
$file_name = str_replace( ".$file_ext", "." . $chunk . ".$unique_hash.$file_ext", $file_name );
211213
$file_path = $file_dir_path . $file_name;
212214

213215
// Make sure the fileName is unique but only if chunking is disabled
@@ -299,7 +301,45 @@ function ppom_upload_file() {
299301
}
300302

301303
// Check if file has been uploaded
302-
if ( ! $chunks || $chunk == $chunks - 1 ) {
304+
if ( ! $chunks || $chunk === $chunks - 1 ) {
305+
306+
// Gather all the chunks and combine them into a single file.
307+
$final_file = fopen($file_path, 'wb');
308+
if ( $final_file ) {
309+
$chunks_files_path = [];
310+
$dir = opendir($file_dir_path);
311+
if ($dir) {
312+
while (($file = readdir($dir)) !== false) {
313+
$tmpfilePath = $file_dir_path . $file;
314+
315+
if ( false !== strpos($tmpfilePath, $original_name) && false !== strpos($tmpfilePath, '.part')) {
316+
$chunks_files_path[] = $tmpfilePath;
317+
}
318+
}
319+
closedir($dir);
320+
}
321+
322+
sort( $chunks_files_path );
323+
324+
foreach( $chunks_files_path as $tmpfilePath ) {
325+
$chunk_file = fopen($tmpfilePath, 'rb');
326+
if ($chunk_file) {
327+
while ($buffer = fread($chunk_file, 4096)) {
328+
fwrite($final_file, $buffer);
329+
}
330+
fclose($chunk_file);
331+
// Optionally, you can delete the chunk file after appending it to the final file
332+
unlink($tmpfilePath);
333+
} else {
334+
die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to open chunk file."}, "id" : "id"}');
335+
}
336+
}
337+
338+
fclose($final_file);
339+
} else {
340+
die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "Failed to open final file."}, "id" : "id"}');
341+
}
342+
303343
// Strip the temp .part suffix off
304344
rename( "{$file_path}.part", $file_path );
305345

0 commit comments

Comments
 (0)