chunk.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. // (a) helper function - server response
  3. function verbose($ok = 1, $info = "")
  4. {
  5. if ($ok == 0) {
  6. http_response_code(400);
  7. }
  8. exit(json_encode(["ok" => $ok, "info" => $info]));
  9. }
  10. // (b) invalid upload
  11. if (empty($_FILES) || $_FILES["file"]["error"]) {
  12. verbose(0, "Failed to move uploaded file.");
  13. }
  14. // (c) upload destination - change folder if required!
  15. $filePath = __DIR__ . DIRECTORY_SEPARATOR . "uploads";
  16. /*if (!file_exists($filePath)) {
  17. if (!mkdir($filePath, 0777, true)) {
  18. verbose(0, "Failed to create $filePath");
  19. }
  20. }*/
  21. $fileName = isset($_REQUEST["name"])
  22. ? $_REQUEST["name"]
  23. : $_FILES["file"]["name"];
  24. $filePath = $filePath . DIRECTORY_SEPARATOR . $fileName;
  25. // (d) deal with chunks
  26. $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
  27. $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
  28. $out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
  29. if ($out) {
  30. $in = @fopen($_FILES["file"]["tmp_name"], "rb");
  31. if ($in) {
  32. while ($buff = fread($in, 4096)) {
  33. fwrite($out, $buff);
  34. }
  35. } else {
  36. verbose(0, "Failed to open input stream");
  37. }
  38. @fclose($in);
  39. @fclose($out);
  40. @unlink($_FILES["file"]["tmp_name"]);
  41. } else {
  42. verbose(0, "Failed to open output stream");
  43. }
  44. // (e) check if file has been uploaded
  45. if (!$chunks || $chunk == $chunks - 1) {
  46. rename("{$filePath}.part", $filePath);
  47. }
  48. verbose(1, "Upload OK");
  49. ?>