S3CorsUploadAjaxController.php in Flysystem - S3 8
File
src/Controller/S3CorsUploadAjaxController.php
View source
<?php
namespace Drupal\flysystem_s3\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\file\Entity\File;
use Drupal\flysystem\FlysystemFactory;
use Drupal\Core\File\FileSystemInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Aws\S3\PostObjectV4;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
class S3CorsUploadAjaxController extends ControllerBase {
protected $flysystemFactory;
protected $fileSystem;
public static function create(ContainerInterface $container) {
return new static($container
->get('flysystem_factory'), $container
->get('file_system'));
}
public function __construct(FlysystemFactory $flysystem_factory, FileSystemInterface $file_system) {
$this->flysystemFactory = $flysystem_factory;
$this->fileSystem = $file_system;
}
public function signRequest(Request $request) {
$post = $request->request
->all();
$scheme = \Drupal::service('file_system')
->uriScheme($post['destination']);
$adapter = $this->flysystemFactory
->getPlugin($scheme)
->getAdapter();
$client = $adapter
->getClient();
$bucket = $adapter
->getBucket();
$destination = $adapter
->applyPathPrefix(StreamWrapperManager::getTarget($post['destination']));
$options = [
[
'acl' => $post['acl'],
],
[
'bucket' => $bucket,
],
[
'starts-with',
'$key',
$destination . '/',
],
];
$uri = \Drupal::service('file_system')
->createFilename($post['filename'], $post['destination']);
$post['key'] = $adapter
->applyPathPrefix(StreamWrapperManager::getTarget($uri));
$file = File::create([
'uri' => $post['key'],
'filesize' => $post['filesize'],
'filename' => $post['filename'],
'filemime' => $post['filemime'],
'uid' => \Drupal::currentUser()
->getAccount()
->id(),
]);
$file
->save();
unset($post['destination']);
unset($post['filename']);
unset($post['filemime']);
unset($post['filesize']);
$expiration = '+5 hours';
$postObject = new PostObjectV4($client, $bucket, $post, $options, $expiration);
$data = [];
$data['attributes'] = $postObject
->getFormAttributes();
$data['inputs'] = $postObject
->getFormInputs();
$data['options'] = $options;
$data['fid'] = $file
->id();
return new JsonResponse($data);
}
}