I am developing a file system management using laravel 8.
I created a function that accept file.
public function uploadExperiment(Request $request)
{
$file = $request->file('file');
$uniqueId = time();
$fileName = $file->getClientOriginalName();
$filePath = $uniqueId . '/' . $fileName;
Storage::disk('local')->put($filePath, file_get_contents($file));
return response()->json(["success"=>true]);
}
I need to track the uploaded size during the uploading process and this progress I need to save it in a database.
For example, If I want to upload a file with 2GB of size, It will takes time. So any idea about how to track it?
My Answer:
You can track the uploaded size of a file by using the `getSize()` method of the uploaded file object. Here's how you can modify your `uploadExperiment` function to track the uploaded size and save it in a database:
php
public function uploadExperiment(Request $request)
{
$file = $request->file('file');
$uniqueId = time();
$fileName = $file->getClientOriginalName();
$filePath = $uniqueId . '/' . $fileName;
$totalSize = $file->getSize();
$uploadedSize = 0;
$stream = fopen($file, 'r');
while (!feof($stream)) {
$chunk = fread($stream, 1024); // Read 1KB at a time
$uploadedSize += strlen($chunk);
// Save the uploaded size in the database
// You can save it in a separate table or in the same table where you store the file information
// Example: FileUploadProgress::create(['file_path' => $filePath, 'uploaded_size' => $uploadedSize]);
Storage::disk('local')->append($filePath, $chunk); // Append the chunk to the file
// You can also send the progress to the client using websockets or AJAX
// Example: event(new FileUploadProgressEvent($uploadedSize, $totalSize));
// You can also use a queue to handle the file upload process asynchronously
}
fclose($stream);
return response()->json(["success" => true]);
}
In this modified function, we calculate the total size of the uploaded file using the `getSize()` method. We then read the file in chunks of 1KB and update the `uploadedSize` variable accordingly. You can save the `uploadedSize` in the database or send it to the client using websockets or AJAX for real-time progress tracking.
Make sure to adjust the code according to your database structure and how you want to handle the progress tracking.
Rate this post
5 of 5 based on 9792 votesComments