Categories: Development

How to get upload speed from a file upload in Laravel

A neat concept to get file upload speed when uploading files from a form in Laravel.

This base method will also work when uploading to an SFTP server using PHP or downloading from one too.

The only requirements are the uploaded file size and a timer on how long the upload process took.

Note that is example is bare bones with no true validation on accepted upload file size or type.

In the file upload controller method validate the file from the file input named selected_file and get the files size as bytes and its original name:

$request->validate([
    'selected_file' => 'file|required',
]);

$file = $request->file('selected_file');
$file_size = $file->getSize();
$original_name = $file->getClientOriginalName();

Now start the timer and store the file from the upload, the timer is to calculate the upload speed it is also handy to know how long the upload took in seconds.

Calculating the upload speed as Mbps is done by dividing the file size with the duration, this returns Bps.

Converting this to a more human-readable format as Mbps can be done by dividing by 1000 twice

$start_timer = time();

$store = $file->storeAs("uploads", $original_name, 'private');

$end_timer = time() - $start_timer;
$upload_speed_mbps = number_format(($file_size / $end_timer / 1000 / 1000), 2);

if ($store) {
    return "Uploaded $original_name in $end_timer seconds at $upload_speed_mbps Mbps";
}

return "File $original_name could not be uploaded";

A message is then returned depending on if the file store was successful or not.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago