Skip to content

Instantly share code, notes, and snippets.

@carestad
Last active November 6, 2019 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carestad/51a705141ec3ddfcb0a720e3a199ee65 to your computer and use it in GitHub Desktop.
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.
<?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);
}
}
@carestad
Copy link
Author

carestad commented Jan 4, 2019

Please note that this does not currently work.

It does now!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment