-2

I'm getting binary response from third party API via HTTP CLIENT in Symfony

How to convert that response to a UplodedFile Object.

Please suggest a good way to do this.

Ravi Damasiya
  • 484
  • 2
  • 13
  • 1
    Looking at [the code](https://github.com/symfony/symfony/blob/6.2/src/Symfony/Component/HttpFoundation/File/UploadedFile.php), seems like you can instantiate it yourself. I think you need to set `test` to `true` however. – Chris Haas Jun 11 '22 at 14:16

1 Answers1

2

You can't use the UploadedFile class, since that requires a file path and will throw an error (on move) if you try to pass it a path to a file that wasn't uploaded via the $_FILES array.

Alternatively, you can use Symfony's File class (UploadedFile extends File), but that also requires a file path. So you'll need to convert the response to a (temporary) file, for example using the class below.

Since this class extends File, you can validate instances of it using the Symfony Validator and call move on it, just as you would with an UploadedFile.

use Symfony\Component\HttpFoundation\File\File;

class TmpFile extends File {

    private $handle;

    public function __construct(string $contents)
    {
        $this->handle = tmpfile();
        fwrite($this->handle, $contents);
        
        parent::__construct(stream_get_meta_data($this->handle)['uri']);
    }

}

And use it like this: $tmpFile = new TmpFile((string) $response->getContent());

Marleen
  • 2,245
  • 2
  • 13
  • 23