How to upload file in laravel through an API?
This article provides a comprehensive guide on how to upload a file in Laravel through an API. The file will be uploaded in text format using the base64 encoding method. Subsequently, we will decode the base64 text and convert it back to its original format before saving it.
So lets get started first we will create a controller to use the command below :
php artisan make:controller Api/FileUploadController
A controller file has been created in app/Http/Controllers/Api/FileUploadController.php now we will add route in /routes/api.php
Route::post('file-upload', [\App\Http\Controllers\Api\FileUploadController::class, 'store']);
This code is used to handle a file upload where the file is sent as a base64 encoded string in the request. It checks if the file has a valid extension, decodes the base64 string, and then saves the file to a disk. If the file extension is not valid, it returns an error response. user What is base64 encoding? Base64 encoding is a method of converting binary data into a safe format for transmission over systems that are designed to handle text. This encoding helps to ensure that the data remains intact without modification during transport.
Base64 is used commonly in a number of applications including email via MIME, as well as storing complex data in XML or JSON.
In Base64 encoding, the binary data is represented as a string of characters from the set: A-Z, a-z, 0-9, +, and /. The = character is used as padding.
Itâs important to note that Base64 is not an encryption or hashing method, and should not be used for password or security purposes. It is a binary-to-text encoding scheme that is primarily used to encode binary data for use in text fields.
public function store(Request $request)
{
// Get the base64 encoded file from the request
$file_64 = $request->profile;
// Extract the file extension from the base64 string
$extension = explode('/', explode(':', substr($file_64, 0, strpos($file_64, ';')))[1])[1];
// Define the valid file extensions
$validateExt = [
'jpeg',
'png',
'jpg',
];
// Check if the file has a valid extension
if(in_array($extension, $validateExt))
{
// Remove the data URL declaration from the base64 string
$replace = substr($file_64, 0, strpos($file_64, ',') + 1);
$file = str_replace($replace, '', $file_64);
// Replace spaces with '+' to correct the base64 encoding
$file = str_replace(' ', '+', $file);
// Generate a unique filename using the current timestamp and a random number
$fileNameToStores = time() . rand(0,9999) . '.' . $extension;
// Save the file to the 'public' disk (defined in config/filesystems.php)
\Storage::disk('public')->put($fileNameToStores, base64_decode($file));
// save data here
//$user = new User();
//$user->profile = $fileNameToStores;
//$user->name = $request->name;
//$user->save();
// return a success response
return response()->json([
'status' => 'success',
'message' => 'File uploaded successfully'
]);
}
else
{
// If the file extension is not valid, return an error response
return response()->json([
'status' => 'error',
'message' => 'File must be type of ' . implode(',',$validateExt)
]);
}
}
Now you can pass file as text in postman or any other way using base64 encoding which will look somthing like this.
data:image/png;base64,iVBORw0KGgoAAAA.....
In postman you can pass it like this.
- If you want to save a file from url then please checkout this post.
- If you want to upload image in summernote then please checkout this post.
Tags
Related Posts
How to edit env dynamically in laravel?
How to integrate ChatGPT into Laravel?
How to create multi auth in laravel with 2 different login page?
How to use seeder in laravel?
How to run laravel 10 project without artisan serve?
How to upload file in laravel through an API?
How to us factory in laravel?
How to integrate ChatGPT image generation into Laravel?
Most Useful Laravel Commands
How to create a custom helper file and function in Laravel?