Reputation: 996
In my Laravel project I need to upload mp3 files, However Laravel using mpga
as a mime type to validate mp3
files type I found that in this answer.
$results = Validator::make($request->all(), [
"song" => "required|file|mimes:mpga|max:8192",
]);
I am okay with that but my problem is the file is stored with mpga
extension, I know the reason behind this weird action from this answer.
How I store the file
// Upload the song
$filePath = $request->song->store("public/songs");
But I want to store the file with mp3
extension.
Upvotes: 0
Views: 1489
Reputation: 6272
Lobsterbaz's answer works perfectly, and i also want to give alternative to that answer which will help you to keep your file's extension as it is.
Laravel changes mp3
file's extension as mpga
after uploading, so here i will show you how to keep mp3 file's extension as it is after uploading, below code will help you to do it:
use Illuminate\Support\Str;
$path = $request->file('song')->storeAs(
'songs', Str::random(40).".mp3"
);
Congrats, Now your song will be stored as mp3, but be sure to upload mp3 files only and put validation of mimes for mp3 otherwise it can break the file.
Upvotes: 0
Reputation: 2003
Without seeing your code, the best I can suggest is to use the putFileAs() method from the Storage
class.
This method allows you to specify a file name when storing your file:
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
// Manually specify a file name:
Storage::putFileAs(
'folder',
new File('/path/to/uploaded-music.mp3'),
'stored-song-name.mp3'
);
See Laravel doc: https://laravel.com/docs/5.8/filesystem#storing-files
Edit: If you want to keep Laravel random file naming just like the putFile()
method does, you can generate a random string and append your extension:
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
// Manually specify a file name:
Storage::putFileAs(
'folder',
new File('/path/to/uploaded-music.mp3'),
Str::random(40) . '.mp3'
);
If you look at Laravel source code, this is how putFile()
does it to generate a random file name.
Upvotes: 1