deepseek-1.x-dev/src/Controller/FileUploadController.php

src/Controller/FileUploadController.php
<?php

namespace Drupal\deepseek\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\File\FileExists;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\File\FileUrlGeneratorInterface;
use Drupal\file\FileRepositoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Controller for handling file uploads.
 */
class FileUploadController extends ControllerBase {

  /**
   * Constructs a new FileUploadController.
   *
   * @param \Drupal\file\FileRepositoryInterface $fileRepository
   *   The file repository service.
   * @param \Drupal\Core\File\FileUrlGeneratorInterface $fileUrlGenerator
   *   The file URL generator service.
   * @param \Drupal\Core\File\FileSystemInterface $fileSystem
   *   The file system generator service.
   */
  public function __construct(protected FileRepositoryInterface $fileRepository, protected FileUrlGeneratorInterface $fileUrlGenerator, protected FileSystemInterface $fileSystem) {
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('file.repository'),
      $container->get('file_url_generator'),
      $container->get('file_system'),
    );
  }

  /**
   * Handles file upload requests.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The HTTP request object.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The JSON response with file details or error message.
   */
  public function upload(Request $request) {
    $file = $request->files->get('file');

    if ($file && $file->isValid()) {
      try {
        // Save the file using FileRepository, which handles naming conflicts.
        $file_entity = $this->fileRepository->writeData(
          file_get_contents($file->getPathname()),
          'temporary://' . $file->getClientOriginalName(),
          FileExists::Replace
        );
        $file_entity->setPermanent(FALSE);
        $file_entity->save();

        if ($file_entity) {
          // Generate the absolute PATH for the file.
          $name = $file->getClientOriginalName();
          $path = $this->fileSystem->realpath($file_entity->getFileUri());
          return new JsonResponse([
            'fid' => $file_entity->id(),
            'name' => $name,
            'path' => $path,
          ]);
        }
      }
      catch (\Exception $e) {
        return new JsonResponse(['error' => 'File upload failed: ' . $e->getMessage()], 400);
      }
    }

    return new JsonResponse(['error' => 'Invalid file upload'], 400);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc