Reputation: 1
I am working on a Laravel project where users can upload various types of files, including images, documents, and videos. I want to ensure that each uploaded file has a unique filename to avoid overwriting existing files with the same name.
I have already implemented the file upload functionality using Laravel's built-in Storage facade, but I'm struggling with generating and storing unique filenames for each uploaded file. I want to maintain the original file extension and ensure that the filenames are not too long.
Here's a simplified version of my current code:
**public function uploadFile(Request $request) { $file = $request->file('file');
if ($file) {
$originalName = $file->getClientOriginalName();
// Need help generating a unique filename here
$uniqueFilename = // ??? How to generate a unique filename with the original extension?
$file->storeAs('uploads', $uniqueFilename, 'public');
}
return response()->json(['message' => 'File uploaded successfully']);
}**
I'm looking for a solution that:
-Generates a unique filename for each uploaded file. -Retains the original file extension. -Ensures that the generated filename is not excessively long. -Avoids conflicts in case two users upload files with the same name simultaneously.
Any suggestions or code examples on how to achieve this in Laravel would be greatly appreciated. Thank you!
Upvotes: 0
Views: 396
Reputation: 720
I usually use time()
function from PHP to ensure that a unique filename is being generated. You could probably use some thing as below. The code is untested though, but i have used it in my projects
// first thing first, lets use early exit strategy to get rid of conditional
if ( !$file ) {
return response()->json(['message' => 'Problem with uploading file']);
}
// lets get the name of file without extension
$originalName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
// Lets generate unique filename even if two files with same name are uploaded
$uniqueFilename = $originalName . '_' . time() . '_' . Str::random(5) . '.' . $file->getClientOriginalExtension();
// By the way some people use md5 too as below
$uniqueHash = md5($originalName . '_' . time() . '_' . Str::random(5));
$uniqueFileName = $uniqueHash. '.' .$file->getClientOriginalExtension();
// Rest of the code to upload file and then send back response
Upvotes: 0