Skip to content

Commit

Permalink
[HttpFoundation] Fix deleteFileAfterSend on client abortion
Browse files Browse the repository at this point in the history
  • Loading branch information
nerg4l committed Jul 8, 2021
1 parent 09814d5 commit a579bbe
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/Symfony/Component/HttpFoundation/BinaryFileResponse.php
Expand Up @@ -34,6 +34,7 @@ class BinaryFileResponse extends Response
protected $offset = 0;
protected $maxlen = -1;
protected $deleteFileAfterSend = false;
protected $chunkSize = 1024 * 1024;

/**
* @param \SplFileInfo|string $file The file to stream
Expand Down Expand Up @@ -124,6 +125,22 @@ public function getFile()
return $this->file;
}

/**
* Sets the response stream chunk size.
*
* @return $this
*/
public function setChunkSize(int $chunkSize)
{
if ($chunkSize < 1 || $chunkSize > \PHP_INT_MAX) {
throw new \LogicException('The chunk size of a BinaryFileResponse cannot be less than 1 or greater than PHP_INT_MAX.');
}

$this->chunkSize = $chunkSize;

return $this;
}

/**
* Automatically sets the Last-Modified header according the file modification date.
*/
Expand Down Expand Up @@ -303,7 +320,23 @@ public function sendContent()
$out = fopen('php://output', 'w');
$file = fopen($this->file->getPathname(), 'r');

stream_copy_to_stream($file, $out, $this->maxlen, $this->offset);
ignore_user_abort(true);

if (0 !== $this->offset) {
fseek($file, $this->offset);
}

$length = $this->maxlen;
while ($length && !feof($file)) {
$read = ($length > $this->chunkSize) ? $this->chunkSize : $length;
$length -= $read;

stream_copy_to_stream($file, $out, $read);

if (connection_aborted()) {
break;
}
}

fclose($out);
fclose($file);
Expand Down

0 comments on commit a579bbe

Please sign in to comment.