How to get the size of an uploaded file in Laravel in the best way?

We have learnt of many ways to upload files, images and videos in Laravel. Laravel applications have built in functions to perform many tasks. We have functions to create database migrations, validate data, and so. Similarly, we have methods to read the size of an uploaded file in Laravel.

Using the getSize() method

You can apply the getSize() function on an uploaded file or even before uploading the file, for the purpose of validation.

The code for the function is as shown in a Controller class, as shown below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileController extends Controller
{
    public function save(Request $request)
    {
         $fileSize = $request->file('file')->getSize();
    }
}

Request object reads the file data. We will apply the getSize() function on the file from the request object. The size returned is passed to the $fileSize variable.

File size information is to avoid upload fails for heavy files or videos and to assure uploaded data meets server and application storage criteria.

The method getClientSize() was used for this function in Laravel 4, but got depreciated in Laravel 5.

Using the Storage Façade

A more simple way is to use Storage Façade if your file is already stored / uploaded in the Laravel application.

use Illuminate\Support\Facades\Storage;

public function get_file_size($file_path)
{
    return Storage::size($file_path);
}

As shown above, you just need to return the file path in the Storage::size façade. It returns back the file size in the function defined.

Leave a Comment