Last active
November 13, 2020 10:04
-
-
Save tlorens/5c97ea88b2f8081e4f2a74266fbf50d2 to your computer and use it in GitHub Desktop.
Guzzle 6 Large file uploads / Chunking
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
/** | |
* @Route("/chunks", name="chunks") | |
*/ | |
public function sendFileAction() | |
{ | |
$jar = new \GuzzleHttp\Cookie\SessionCookieJar('SESSION_STORAGE', true); | |
$handler = new CurlHandler(); | |
$stack = HandlerStack::create($handler); | |
$client = new Client(['cookies'=>true, 'handler' => $stack]); | |
$filename = 'files/huge-1gig-file.jpg'; | |
$filesize = filesize($filename); | |
$fh = fopen($filename, 'r'); | |
$chunkSize = 1024 * 2000; | |
$boundary = '----iCEBrkUploaderBoundary' . uniqid(); | |
$url = 'https://localhost/app_dev.php/_uploader/bigupload/upload'; | |
rewind($fh); // probably not necessary | |
while (! feof($fh)) { | |
$pos = ftell($fh); | |
$chunk = fread($fh, $chunkSize); | |
$calc = $pos + strlen($chunk)-1; | |
// Not sure if this is needed. | |
if (ftell($fh) > $chunkSize) { | |
$pos++; | |
} | |
$request = $client->request( | |
'POST', | |
$url, | |
[ | |
'cookies' => $jar, | |
'debug' => false, | |
'verify' => false, | |
'headers' => [ | |
'Transfer-Encoding' => 'chunked', | |
'Accept-Encoding' => 'gzip, deflate, br', | |
'Accept' => 'application/json, text/javascript, */*; q=0.01', | |
'Connection' => 'keep-alive', | |
'Content-disposition' => 'attachment; filename="' . basename($filename) . '"', | |
'Content-length' => $calc - $pos, | |
'Content-Range' => 'bytes ' . $pos . '-' . $calc . '/' . $filesize | |
], | |
'multipart' => [ | |
[ | |
'name' => 'api_key, | |
'contents' => 'aaabbbcc-deff-ffed-dddd-1234567890123' | |
], | |
[ | |
'name' => 'file', | |
'contents' => $chunk, | |
'filename' => basename($filename), | |
'headers' => [ | |
'Content-Type' => 'multipart/form-data; boundary=' . $boundary | |
] | |
] | |
] | |
] | |
); | |
} | |
return new Response('ok', 200); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment