Last active
November 6, 2019 12:09
-
-
Save carestad/51a705141ec3ddfcb0a720e3a199ee65 to your computer and use it in GitHub Desktop.
Middleware to detect if a POST parameter of a given type is present, and if it is a data URI string we convert it to an instance of UploadedFile and make it accessible via Laravel's Request class and the file handling methods there.
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
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Http\UploadedFile; | |
class DataUriToFile | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @param string $field | |
* @return mixed | |
* @example Route::post()->middleware('DataUriToFile:image') | |
*/ | |
public function handle($request, Closure $next, string $field) | |
{ | |
if ($request->has($field) && substr($request->{$field}, 0, 11) === 'data:image/') { | |
$dataUri = $request->{$field}; | |
$tempFile = tempnam(sys_get_temp_dir(), 'laravel-data-uri-'); | |
$file = file_get_contents($dataUri); | |
file_put_contents($tempFile, $file); | |
$fileMime = mime_content_type($tempFile); | |
// Add the converted file to request object | |
$request->files->add([ | |
$field => new UploadedFile($tempFile, 'image', $fileMime, strlen($file)), | |
]); | |
// Unset/remove the original parameter | |
$request->offsetUnset($field); | |
} | |
return $next($request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please note that this does not currently work.It does now!