Created
November 30, 2015 09:37
-
-
Save widnyana/cd2bdda07dc02e9fce71 to your computer and use it in GitHub Desktop.
Lumen Framework - Send Image via ResponseStream
This file contains hidden or 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
<?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