Skip to content

Instantly share code, notes, and snippets.

@widnyana
Created November 30, 2015 09:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save widnyana/cd2bdda07dc02e9fce71 to your computer and use it in GitHub Desktop.
Save widnyana/cd2bdda07dc02e9fce71 to your computer and use it in GitHub Desktop.
Lumen Framework - Send Image via ResponseStream
<?php
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class XController
{
public function getView(Request $r, $loc='')
{
// $loc = absulute path to file
$file = fopen($loc, "rb");
$size = filesize($loc);
$content = fread($file, $size);
fclose($file);
// mock mimetype, pls use finfo_open()
$mime = "image/png";
return $this->streamFile($r, $mime, $content, $size);
}
// Provide a streaming file with support for scrubbing
private function streamFile(Request $r, $contentType, $stream, $fullsize ) {
$size = $fullsize;
$response_code = 200;
$headers = array("Content-type" => $contentType);
// Check for request for part of the stream
$range = $r->header('Range');
if($range != null) {
$eqPos = strpos($range, "=");
$toPos = strpos($range, "-");
$unit = substr($range, 0, $eqPos);
$start = intval(substr($range, $eqPos+1, $toPos));
$success = fseek($stream, $start);
if($success == 0) {
$size = $fullsize - $start;
$response_code = 206;
$headers["Accept-Ranges"] = $unit;
$headers["Content-Range"] = $unit . " " . $start . "-" . ($fullsize-1) . "/" . $fullsize;
}
}
$headers["Content-Length"] = $size;
$response = new StreamedResponse(
function () use ($stream) {
$out = fopen('php://output', 'w');
fputs($out, $stream);
fclose($out);
}, 200, $headers);
$response->send();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment