Score:0

How do i save a base64 decoded image to file_managed?

cn flag

I'm trying to save my image to Drupal's file_managed table. However, my image is coming from base64 decode:

 $filename = "sign-".$user->id(); // returns "sign-1234"
 $image_raw = $form_state->getValue('signature'); // returns base64 string of png
 $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $image_raw));
 $image = file_put_contents('private://requestformfiles/'.$filename.'.png', $data);

 $file = File::load($image); // does not get anything
 $file->setPermanent(); // fails
 $file->save(); 

 $result = $connection->insert('request_id')
        ->fields([
            ...
            'signature' => $image,
            ...
        ])
        ->execute();

From what i see, My file successfully uploads into the private files folder, and image returns a random 4 digit number. However, when setting it to file_managed in the Database, it fails, since File::load cannot see my $image.

Any help is again, appreciated.

Score:1
cn flag

I actually didn't have to use File entity for this, what i actually needed was file_save_data()

$filename = "nrsign-".$user->id();
$files_data = preg_replace('#^data:application/\w+;base64,#i', '', $image_raw);
$file_data = base64_decode($files_data);
$file = file_save_data($file_data, "private://requestformfiles/".$filename.".png", FILE_EXISTS_RENAME);

echo $file->id();

file_save_data creates the file and saves a record in files_managed as well. $file->id(); returns the $fid for the created file.

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.