Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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