php-crud-api icon indicating copy to clipboard operation
php-crud-api copied to clipboard

Returning user uploaded file using custom controller

Open chattago2002 opened this issue 1 year ago • 2 comments

Hi everybody.

I made a custom controller to handle file uploads and I'd like to add the capability to return the file via API made using this repository. In the function __construct function I added:

$router->register('GET', '/records/file/*', array($this, 'getFileV2'));

In

public function getFileV2(ServerRequestInterface $request): ResponseInterface

I need to get the file, decrypt (because in POST controller function the file is correctly uploaded as encrypted) but also if I add

header("Content-Type: image/png");
return $decryptedFile;

I can't view the file and the error message is:

UploadUserFile::getFileV2(): Return value must be of type Psr\\Http\\Message\\ResponseInterface, string returned

How can I do this?

chattago2002 avatar Apr 02 '24 13:04 chattago2002

Good question, you shouldn't return a string. Try this:

return ResponseFactory::from(200, "image/png", $decryptedFile);

You can see some response fiddling in the XmlMiddleware, see:

https://github.com/mevdschee/php-crud-api/blob/main/src/Tqdev/PhpCrudApi/Middleware/XmlMiddleware.php

You can read more about PSR7 in de dependency:

https://github.com/Nyholm/psr7

mevdschee avatar Apr 02 '24 18:04 mevdschee

Good question, you shouldn't return a string. Try this:

return ResponseFactory::from(200, "image/png", $decryptedFile);

You can see some response fiddling in the XmlMiddleware, see:

https://github.com/mevdschee/php-crud-api/blob/main/src/Tqdev/PhpCrudApi/Middleware/XmlMiddleware.php

You can read more about PSR7 in de dependency:

https://github.com/Nyholm/psr7

Thanks for reply. I'll try in a few days and then let know.

chattago2002 avatar Apr 08 '24 09:04 chattago2002