PHP code example of hkreuter / graphql-upload

1. Go to this page and download the library: Download hkreuter/graphql-upload 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/ */

    

hkreuter / graphql-upload example snippets


use Application\Action\GraphQLAction;
use Mezzio\Helper\BodyParams\BodyParamsMiddleware;
use GraphQL\Upload\UploadMiddleware;

$app->post('/graphql', [
    BodyParamsMiddleware::class, 
    UploadMiddleware::class, // This is the magic
    GraphQLAction::class,
], 'graphql');



use GraphQL\Server\StandardServer;
use GraphQL\Upload\UploadMiddleware;
use Laminas\Diactoros\ServerRequestFactory;

// Create request (or get it from a framework)
$request = ServerRequestFactory::fromGlobals();
$request = $request->withParsedBody(json_decode($request->getBody()->getContents(), true));

// Process uploaded files
$uploadMiddleware = new UploadMiddleware();
$request = $uploadMiddleware->processRequest($request);

// Execute request and emits response
$server = new StandardServer(/* your config here */);
$result = $server->executePsrRequest($request);
$server->getHelper()->sendResponse($result);



use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
use GraphQL\Upload\UploadType;
use Psr\Http\Message\UploadedFileInterface;

// Build your Schema
$schema = new Schema([
    'query' => new ObjectType([
        'name' => 'Query',
    ]),
    'mutation' => new ObjectType([
        'name' => 'Mutation',
        'fields' => [
            'testUpload' => [
                'type' => Type::string(),
                'args' => [
                    'text' => Type::string(),
                    'file' => new UploadType(),
                ],
                'resolve' => function ($root, array $args): string {
                    /** @var UploadedFileInterface $file */
                    $file = $args['file'];

                    // Do something with the file
                    $file->moveTo('some/folder/in/my/project');

                    return 'Uploaded file was ' . $file->getClientFilename() . ' (' . $file->getClientMediaType() . ') with description: ' . $args['text'];
                },
            ],
        ],
    ]),
]);