Laravel File Storage: How to store (decoded) base64 image?
When handling image uploads, you often encounter scenarios where the data arrives as a Base64 string rather than a raw binary stream or a traditional multipart/form-data request. While decoding this string with base64_decode() yields valid binary data, Laravel's storage facade expects an instance of Illuminate\Http\File or Illuminate\Http\UploadedFile. This mismatch creates a specific constraint: you cannot simply pass the decoded bytes to Storage::disk()->put(), nor can you pass the raw Base64 string directly.
The core challenge lies in bridging the gap between decoded binary data and Laravel's file object abstraction. To store a Base64 image using Laravel's filesystem methods, you must reconstruct a valid File instance or manipulate the storage stream directly to accept the raw bytes.
Reconstructing an UploadedFile Instance
One approach involves creating an artificial UploadedFile object. This is useful if your application logic expects specific methods from the UploadedFile class, such as checking file size or MIME type before storage. You can instantiate this object by pointing it to a temporary stream containing the decoded data.
First, decode the Base64 string and write it to a temporary resource. Then, wrap that resource in an UploadedFile. The constructor for UploadedFile accepts a filename, a file path (or resource), a MIME type, and flags indicating if the file was successfully uploaded via HTTP. For local storage, you can set the isValid() flag to true manually since this data isn't coming from a standard form POST.
use Illuminate\Http\UploadedFile;
$encodedImage = $request->input('image'); // The Base64 string without data URI prefix
// Ensure we only process the actual image part if it includes 'data:image/...'
if (preg_match('/^data:image\/(\w+);base64,/', $encodedImage, $type)) {
$encodedImage = substr($encodedImage, strpos($encodedImage, ',') + 1);
$mimeType = 'image/' . preg_replace('/\//', '', $type[1]);
} else {
$mimeType = 'application/octet-stream'; // Fallback if no header is found
}
$decodedData = base64_decode($encodedImage);
// Create a temporary stream to hold the decoded binary data
$tempFile = tempnam(sys_get_temp_dir(), 'base64_img');
file_put_contents($tempFile, $decodedData);
// Construct the UploadedFile instance
$file = new UploadedFile(
$tempFile,
'image.jpg', // Desired filename
$mimeType,
false, // Do not test for upload errors (we trust the input)
true // Mark as valid since we are handling it manually
);
// Now you can use Laravel's storage facade normally
\Storage::disk('public')->putFileAs(
'uploads',
$file,
'decoded_image.jpg'
);
// Clean up the temporary file immediately after storage
unlink($tempFile);
This method adheres to Laravel's conventions but introduces a minor overhead: creating and deleting a temporary file. If you are processing thousands of images per second, this I/O operation might become a bottleneck.
Direct Stream Manipulation
A more performant alternative, though slightly less "Laravel-like" in terms of object usage, is to bypass the UploadedFile abstraction entirely. The Storage facade allows you to write directly to the disk using put(). By decoding the string and passing the raw bytes to put(), you avoid creating any intermediate file objects or temporary files.
However, this requires you to manage the filename yourself if you are not overwriting an existing file. If you need to store it with a specific name, simply pass the decoded string directly.
use Illuminate\Support\Facades\Storage;
$encodedImage = $request->input('image');
// Strip data URI prefix if present
if (preg_match('/^data:image\/(\w+);base64,/', $encodedImage, $type)) {
$encodedImage = substr($encodedImage, strpos($encodedImage, ',') + 1);
}
$decodedData = base64_decode($encodedImage);
// Directly put the binary string into storage
Storage::disk('public')->put(
'uploads/decoded_image.jpg',
$decodedData
);
This approach is efficient and straightforward. It treats the Base64 data exactly like any other file content read from a database or API response. The trade-off here is that you lose the safety checks provided by UploadedFile, such as automatic MIME type validation unless you implement them manually before the storage call. If your application relies on Laravel's built-in security filters for uploads, you would need to replicate those checks (e.g., using mime_content_type()) before invoking put().
Handling Data URI Prefixes
A common pitfall when working with Base64 images is ignoring the data:image/png;base64, prefix. If you attempt to decode the entire string including the header, base64_decode() will throw an exception because it encounters non-base64 characters (like colons and slashes) at the start of the string. Always strip the prefix before decoding. The regex pattern used in the examples above handles this automatically, ensuring the binary data passed to put() or the temporary file is clean.
Conclusion on Storage Strategy
Both methods effectively solve the problem of storing decoded Base64 images using Laravel's filesystem. If your architecture requires strict adherence to UploadedFile contractsâfor instance, if you have middleware that validates $request->file('image')âthe temporary file approach is necessary. Otherwise, direct storage via put() offers a cleaner, more performant path for handling image data received from external sources or forms where the input is known to be Base64 encoded strings.