1. Go to this page and download the library: Download nks-hub/nette-cloudflare-r2 library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
nks-hub / nette-cloudflare-r2 example snippets
use NksHub\NetteCloudflareR2\Client\R2Client;
class MyPresenter extends Nette\Application\UI\Presenter
{
public function __construct(
private R2Client $r2
) {}
public function actionUpload(): void
{
// Upload string content
$url = $this->r2->upload('path/to/file.txt', 'Hello World!');
// Upload from local file
$url = $this->r2->uploadFromPath('images/photo.jpg', '/local/path/photo.jpg');
// Download content
$content = $this->r2->get('path/to/file.txt');
// Download to local file
$this->r2->download('images/photo.jpg', '/local/destination.jpg');
// Delete
$this->r2->delete('path/to/file.txt');
// Check existence
if ($this->r2->exists('path/to/file.txt')) {
// File exists
}
// Get metadata
$metadata = $this->r2->getMetadata('path/to/file.txt');
echo $metadata->getSize();
echo $metadata->getContentType();
echo $metadata->getFormattedSize(); // "1.5 MB"
}
}
use Nette\Http\FileUpload;
use NksHub\NetteCloudflareR2\Client\R2Client;
class GalleryPresenter extends Nette\Application\UI\Presenter
{
public function __construct(
private R2Client $r2
) {}
public function handleUploadPhoto(): void
{
/** @var FileUpload $file */
$file = $this->getHttpRequest()->getFile('photo');
if ($file && $file->isOk() && $file->isImage()) {
// Upload with auto-generated filename
$url = $this->r2->uploadFile($file, 'gallery/' . $this->user->id);
// Save URL to database
$this->galleryRepository->insert([
'user_id' => $this->user->id,
'url' => $url,
]);
$this->flashMessage('Photo uploaded successfully');
}
$this->redirect('this');
}
}
// List with pagination
$result = $r2->list('images/', maxKeys: 100);
foreach ($result['objects'] as $object) {
echo $object->getKey();
echo $object->getSize();
}
if ($result['isTruncated']) {
// Get next page
$nextResult = $r2->list('images/', 100, $result['nextToken']);
}
// List all (auto-pagination)
foreach ($r2->listAll('images/') as $object) {
echo $object->getKey();
}
// Count objects
$count = $r2->count('images/');
use NksHub\NetteCloudflareR2\Client\R2ClientFactory;
class MyService
{
public function __construct(
private R2Client $r2, // Default bucket
private R2ClientFactory $factory
) {}
public function uploadToImages(string $content): string
{
return $this->factory->create('images')->upload('file.jpg', $content);
}
public function uploadToBackups(string $content): string
{
return $this->factory->create('backups')->upload('backup.zip', $content);
}
}