Reputation: 15037
I have saved a file with this command
$newFile = [
'event_id' => $event->id,
'path' => $storePath
];
EventFile::create($newFile);
I can get the path to the file for a link like this:
Storage::disk('public')->url($file->path);
But there is no data about the file size. How can i get the file size in blade view???
Upvotes: 47
Views: 133730
Reputation: 683
If anyone need to get all the files from storage and calculate their sizes.
public function backups()
{
$directory = "backup";
$allFiles = Storage::allFiles($directory);
$files =[];
foreach($allFiles as $file){
$size = Storage::size($file)/1024;
array_push($files,['file'=>$file,'size'=>$size]);
}
return response()->json($files);
}
Upvotes: 0
Reputation: 1939
Laravel 5^
$request->file('file')->getSize(); // in bytes
Laravel 4
$request->file('file')->getClientSize(); // getClientSize() is deprecated in Laravel 5
Upvotes: 117
Reputation: 2823
According to the Laravel Documentation for version 8.0:
When using the local driver, all files that should be publicly accessible should be placed in the storage/app/public directory.
So the root of your local storage here is the public/
directory within storage/app/
You can Specify the method to get file size in your File Model like this
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class File extends Model
{
use HasFactory;
protected $fillable = [
'name',
'file_path'
];
public function getFileSize()
{
// Ensure $this->file_path begins with '/public/';
return Storage::size($this->file_path);
}
}
And use it like this within your blade file
<div>{{ $file->getFileSize() }}</div>
If you use it this way, $this->file_path
must have the format: /public/optional_subdirectory/file_name
Upvotes: 0
Reputation: 61
laravel 8
$imageSize = $request->file('file')->getSize();
$fil->size = number_format($imageSize / 1048576,2);
$file->size My Table Change It With Your DB Table
Upvotes: 5
Reputation: 4035
The more Simpler way is to use Storage Facade
if you have already stored / uploaded file
use Illuminate\Support\Facades\Storage;
public function get_size($file_path)
{
return Storage::size($file_path);
}
Or if you are using S3
Bucket then you can modify the above function like below
use Illuminate\Support\Facades\Storage;
public function get_size($file_path)
{
return Storage::disk('s3')->size($file_path);
}
Check Laravel File Storage
Upvotes: 12
Reputation: 663
getClientSize() is deprecated starting version 4.1. Use getSize() instead.
https://github.com/symfony/symfony/blob/4.1/UPGRADE-4.1.md#httpfoundation
Upvotes: 6
Reputation: 998
Very simple(Proper Laravel Way):
//add this at the top of your controller
use File;
// add this with in your function
$size = File::size($PATH_OF_FILE);
Upvotes: 4