summaryrefslogtreecommitdiffstatshomepage
path: root/core/modules/file/src/Controller/FileWidgetAjaxController.php
blob: 25bc02c3da00e7fc8525233a00816b7087aa03dd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php

namespace Drupal\file\Controller;

use Drupal\Core\StringTranslation\ByteSizeMarkup;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Defines a controller to respond to file widget AJAX requests.
 */
class FileWidgetAjaxController {
  use StringTranslationTrait;

  /**
   * Returns the progress status for a file upload process.
   *
   * @param string $key
   *   The unique key for this upload process.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   A JsonResponse object.
   */
  public function progress($key) {
    $progress = [
      'message' => $this->t('Starting upload...'),
      'percentage' => -1,
    ];

    if (extension_loaded('uploadprogress')) {
      $status = uploadprogress_get_info($key);
      if (isset($status['bytes_uploaded']) && !empty($status['bytes_total'])) {
        $progress['message'] = $this->t('Uploading... (@current of @total)', [
          '@current' => ByteSizeMarkup::create($status['bytes_uploaded']),
          '@total' => ByteSizeMarkup::create($status['bytes_total']),
        ]);
        $progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']);
      }
    }

    return new JsonResponse($progress);
  }

}