lasthourcloud/app/Http/Controllers/UploadController.php

83 lines
2.6 KiB
PHP
Raw Permalink Normal View History

2024-04-11 10:13:11 +00:00
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
2024-06-10 20:43:34 +00:00
use Illuminate\Routing\Controller as BaseController;
2024-04-11 10:13:11 +00:00
use Illuminate\Support\Facades\Storage;
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
class UploadController extends BaseController
{
public function upload(Request $request)
{
$resource = getResourceByUuid(request()->route('databaseUuid'), data_get(auth()->user()->currentTeam(), 'id'));
if (is_null($resource)) {
return response()->json(['error' => 'You do not have permission for this database'], 500);
}
2024-06-10 20:43:34 +00:00
$receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
2024-04-11 10:13:11 +00:00
if ($receiver->isUploaded() === false) {
2024-07-24 12:27:21 +00:00
throw new UploadMissingFileException;
2024-04-11 10:13:11 +00:00
}
$save = $receiver->receive();
if ($save->isFinished()) {
return $this->saveFile($save->getFile(), $resource);
}
$handler = $save->handler();
2024-06-10 20:43:34 +00:00
2024-04-11 10:13:11 +00:00
return response()->json([
2024-06-10 20:43:34 +00:00
'done' => $handler->getPercentageDone(),
'status' => true,
2024-04-11 10:13:11 +00:00
]);
}
// protected function saveFileToS3($file)
// {
// $fileName = $this->createFilename($file);
// $disk = Storage::disk('s3');
// // It's better to use streaming Streaming (laravel 5.4+)
// $disk->putFileAs('photos', $file, $fileName);
// // for older laravel
// // $disk->put($fileName, file_get_contents($file), 'public');
// $mime = str_replace('/', '-', $file->getMimeType());
// // We need to delete the file when uploaded to s3
// unlink($file->getPathname());
// return response()->json([
// 'path' => $disk->url($fileName),
// 'name' => $fileName,
// 'mime_type' => $mime
// ]);
// }
protected function saveFile(UploadedFile $file, $resource)
{
$mime = str_replace('/', '-', $file->getMimeType());
$filePath = "upload/{$resource->uuid}";
2024-06-10 20:43:34 +00:00
$finalPath = storage_path('app/'.$filePath);
2024-04-11 10:13:11 +00:00
$file->move($finalPath, 'restore');
return response()->json([
2024-06-10 20:43:34 +00:00
'mime_type' => $mime,
2024-04-11 10:13:11 +00:00
]);
}
2024-06-10 20:43:34 +00:00
2024-04-11 10:13:11 +00:00
protected function createFilename(UploadedFile $file)
{
$extension = $file->getClientOriginalExtension();
2024-06-10 20:43:34 +00:00
$filename = str_replace('.'.$extension, '', $file->getClientOriginalName()); // Filename without extension
2024-04-11 10:13:11 +00:00
2024-06-10 20:43:34 +00:00
$filename .= '_'.md5(time()).'.'.$extension;
2024-04-11 10:13:11 +00:00
return $filename;
}
}