Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

manually creating an Symfony UploadedFile

I'm facing following problem and can't seem to figure this one out. I wrote an API endpoint accepting a POST with binary data (header: content-type:image/jpeg).

I know i can read out the raw string with file_get_content('php://input') or Laravel's $request->getContent(). PHP also has a function createimagefromstring($string) which also seems to read the string in correctly.

What i'd like to do is create an UploadedFile from this raw data , so that I can handle it with already written functions.

Is this possible?

Thank you in advance

like image 590
Gregory Avatar asked Aug 18 '15 16:08

Gregory


3 Answers

I think I found it... Still curious if there are improvements that can be made..

$imgRaw = imagecreatefromstring( $request->getContent() );
if ($imgRaw !== false) {
    imagejpeg($imgRaw, storage_path().'/tmp/tmp.jpg',100);
    imagedestroy($imgRaw);
    $file =  new UploadedFile( storage_path().'/tmp/tmp.jpg', 'tmp.jpg', 'image/jpeg',null,null,true);
    // DO STUFF WITH THE UploadedFile
}
like image 146
Gregory Avatar answered Nov 18 '22 23:11

Gregory


You can try to use base64 encoding. Symfony have some nice stuff for this.

Your code will be smthng like this:

$base64Content = $request->request->get('base64Content'); // this is your post data
$yourFile = new UploadedBase64EncodedFile(new Base64EncodedFile($base64Content)); // this is an instance of UploadedFile

Hope it helps!

like image 5
Keloo Avatar answered Nov 18 '22 22:11

Keloo


As per Laravel 8

Just follow the constructor:

     * @param string      $path         The full temporary path to the file
     * @param string      $originalName The original file name of the uploaded file
     * @param string|null $mimeType     The type of the file as provided by PHP; null defaults to application/octet-stream
     * @param int|null    $error        The error constant of the upload (one of PHP's UPLOAD_ERR_XXX constants); null defaults to UPLOAD_ERR_OK
     * @param bool        $test         Whether the test mode is active

    $file = new UploadedFile(
        $pathIncludingFilename, 
        $fileName, 
        'image/jpeg', 
        null, 
        false
    );
 
like image 4
digout Avatar answered Nov 18 '22 21:11

digout