手动创建Symfony UploadedFile

Gre*_*ory 18 php symfony laravel-5

我正面临着以下问题,似乎无法想出这个问题.我写了一个API端点接受带有二进制数据的POST(header:content-type:image/jpeg).

我知道我可以用file_get_content('php://input')Laravel's 读出原始字符串$request->getContent().PHP也有一个函数createimagefromstring($string),似乎也正确读取字符串.

我想要做的是从这个原始数据创建一个UploadedFile,这样我就可以用已编写的函数来处理它.

这可能吗?

先感谢您

Gre*_*ory 9

我想我发现了......仍然很好奇是否有可以改进...

$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
}
Run Code Online (Sandbox Code Playgroud)


Kel*_*loo 5

您可以尝试使用 base64 编码。Symfony 为此提供了一些不错的东西。

您的代码将是这样的:

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

希望能帮助到你!


dig*_*out 5

根据 Laravel 8

只需遵循构造函数即可:

     * @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
    );
 
Run Code Online (Sandbox Code Playgroud)