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

Issue

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

Answered By – Marleen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published