phpsymfonysymfony5

Symfony: How to convert binary file response to Uploded File Object


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.


Solution

  • 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());