Multi file upload by base64 url in laravel
Function
function uploadBase64File($base64_url){
$response = array();
$base64Data = $base64_url;
$pattern = '/data:(.*);base64,([^"]*)/';
// Perform the regular expression match
preg_match($pattern, $base64Data, $matches);
if (!empty($matches[1])) {
$mime = $matches[1];
// Remove the data:image/jpeg;base64, part from the string
$mimeToExt = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/bmp' => 'bmp',
'image/webp' => 'webp',
'application/pdf' => 'pdf',
'application/msword' => 'doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
// Add more mappings as needed
];
// Check if the MIME type exists in the mapping
if (isset($mimeToExt[$mime])) {
$extension = $mimeToExt[$mime];
}
$base64Data = str_replace('data:' . $matches[1] . ';base64,', '', $base64Data);
// Decode the base64 data into binary format
$fileData = base64_decode($base64Data);
$urlParts = parse_url($base64Data);
$queryString = $urlParts['query'];
parse_str($queryString, $queryParameters);
$original_filename = uniqid() . "-" . $queryParameters['filename'];
if(empty($queryParameters['filename'])){
// Generate a unique file name for the uploaded file
$original_filename = uniqid() . "." . $extension;
}
$response["file_name"] = $original_filename;
$response["file_extension"] = $extension;
$response["file_data"] = $fileData;
return $response;
}
}
=====================================================
Add base 64 url
$base64url = "";
$Base64File = uploadBase64File($base64url);
if(!empty($Base64File["file_name"])){
$original_filename = $Base64File["file_name"];
$file_extension = $Base64File["file_extension"];
$file_data = $Base64File["file_data"];
$storagePath = "service-requests/location-images" . "/" . $original_filename;
$filePath = Storage::disk('uploads')->put($storagePath, $file_data);
$ServiceRequestsDocs = ServiceRequestsDocs::create([
'file_extensions' => $file_extension,
'file_name' => $original_filename,
'file_path' => $storagePath,
]
);
}
Add below code in config\filesystem.php file
'uploads' => [
'driver' => 'local',
'root' => public_path() .'/upload',
'visibility' => 'public',
]
Add in Model file
public function getFilePathAttribute($file_path)
{
if(!empty($file_path))
{
return $filepath = URL::to('/') . '/upload/' . $file_path;
/* return asset('/upoad/' . $file_path); */
}
}
Comments
Post a Comment