Score:1

How can i store a base64 image to my site's private folder?

cn flag

I'm trying to store a base64 image from a Signature field plugin (the plugin outputs a base64 text). But before i can store it to the private folder, i have to first convert it as a png image. This is how i normally do it if i just upload an image:

    // Signature Field on FormBuilder
    $form['signature'] = [
        '#type' => 'managed_file',
        '#title' => $this->t('Signature'),
        '#upload_location' => 'private://requestformfiles',
        '#upload_validators' => [
        'file_validate_extensions' => ['png jpg',],
        ],
    ];

    // Pre-saving
    $image = $form_state->getValue('signature');
    $file = File::load( $image[0] );
    $file->setPermanent();
    $file->save(); 

But with a base64 image, i have to do this first:

    $image = $form_state->getValue('signature');
    $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $image));
    file_put_contents('storage/signature.png', $data);

My problem is with file_put_contents. The save location is usually done in '#upload_location', but i don't know how to do this in file_put_contents.

Any help is appreciated!

Score:1
cn flag

file_put_contents supports stream wrappers, so:

file_put_contents('private://path/to/storage/signature.png', $data);
cn flag
Dang, didn't know this works too. Now my problem is `File::load` doesn't really "see" my file in `file_put_contents`, so i can't set it in `file_managed`
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.