-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathFormUploadHandler.php
82 lines (67 loc) · 2.52 KB
/
FormUploadHandler.php
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
namespace App\Handler;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Storj\Uplink\Access;
/**
* Minimal example to upload a file via HTML form using PHP-FIG standards.
* Verified working in Mezzio.
*/
class FormUploadHandler implements RequestHandlerInterface
{
private Access $access;
private ResponseFactoryInterface $responseFactory;
public function __construct(Access $access, ResponseFactoryInterface $responseFactory)
{
$this->access = $access;
$this->responseFactory = $responseFactory;
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
switch ($request->getMethod()) {
case 'GET':
return $this->handleGet($request);
case 'POST':
return $this->handlePost($request);
default:
return $this->responseFactory->createResponse(405);
}
}
public function handleGet(ServerRequestInterface $request): ResponseInterface
{
$response = $this->responseFactory->createResponse(200);
$response->getBody()->write(<<<HTML
<form method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple />
<button>Submit</button>
</form>
HTML
);
return $response;
}
public function handlePost(ServerRequestInterface $request): ResponseInterface
{
$project = $this->access->openProject();
$project->ensureBucket('psr');
/** @var $uploadedFile UploadedFileInterface */
foreach ($request->getUploadedFiles() as $uploadedFile) {
$upload = $project->uploadObject('psr', $uploadedFile->getClientFilename());
$upload->writeFromPsrStream($uploadedFile->getStream());
if ($uploadedFile->getClientMediaType()) {
$upload->setCustomMetadata([
'Content-Type' => $uploadedFile->getClientMediaType(),
]);
}
$upload->commit();
}
$nFiles = count($request->getUploadedFiles());
$response = $this->responseFactory->createResponse(200);
$response->getBody()->write("
<p>Your {$nFiles} files haves been uploaded to a global decentralized network.</p>
");
return $response;
}
}