mevdschee / mevdschee/php-crud-api
API for uploading files (of any type)
@mevdschee is already working on this.
Since Feb 9, 2022.
- Dominant language
- PHP
- Stars
- 3.7k
- Forks
- 1k
- Avg merge
- 1h 55m
- Merged PRs (30d)
- 7
Description
I want to share my custom controller to add the api to upload files of any type.
you can use this API http://localhost:8080/api.php/upload with the POST method to send your files, with the variable file(configurable with the "$name_in_files" variable), you will find your files in the directory archive/ (configurable with the "$path" variable).
if you are motivated, then go copy this code and you will have this best API for this wonderful project
namespace ImadDev\CustomController {
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Tqdev\PhpCrudApi\Cache\Cache;
use Tqdev\PhpCrudApi\Column\ReflectionService;
use Tqdev\PhpCrudApi\Controller\Responder;
use Tqdev\PhpCrudApi\Database\GenericDB;
use Tqdev\PhpCrudApi\Middleware\Router\Router;
class MyCustomController {
private $responder;
public function __construct(Router $router, Responder $responder, GenericDB $db, ReflectionService $reflection, Cache $cache)
{
$router->register('POST', '/upload', array($this, 'getUploadFile'));
$this->responder = $responder;
}
public function getUploadFile(ServerRequestInterface $request): ResponseInterface
{
$path = "archive/";
$name_in_files = 'file';
if(!isset($_FILES[$name_in_files])) return $this->responder->error(1003, $name_in_files,['message' => "filename should be 'file'"]);
elseif($_FILES[$name_in_files]['error']!=0) return $this->responder->error(1008, $name_in_files,['message' => "error saving file"]);
elseif(file_exists($path.$_FILES[$name_in_files]['name'])) return $this->responder->error(1009, '',['message' => "filename duplicated : ".$_FILES[$name_in_files]['name']]);
else{
if(!is_dir($path)) mkdir($path);
$name = $_FILES[$name_in_files]['name'];
move_uploaded_file($_FILES[$name_in_files]['tmp_name'],$path.$name);
return $this->responder->success(['message' => "file saved successfully"]);
}
}
}
}
and add this in config parameter:
$config = new Config([
...
'customControllers' => 'ImadDev\CustomController\MyCustomController',
...
]);
the variable $path is to put the folder where the files will be stored (by default "archive/")
and the variable $name_in_files is the name of the variable in you sent with your files (by default "file")
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.