1

I'm struggling to add file to node in code. I know about File::create() but I want to add file to node based on field configuration of the file field on that particular node's content type, and file's data comes as Base64, not URL or form post.

How do you do it? I'm asking as I want to add file via custom REST call as Base64.

I am using the following code.

$node = Node::load($data['case_id']);
$files = $node->field_file;  // unlimited files
/* @var $df \Drupal\field\Entity\FieldConfig */
$df = $node->getFieldDefinition('field_file'); // ??? can i get this config for saving new file?
$file =  file_save_data(base64_decode($data['data']), ??path??);
$files->appendItem($file)->validate();
$node->save();

Am I on the valid course? I have no clue how to set config from $df and before save. How do I use the configuration of that file field during save?

Yurii

3
  • I'm pretty sure Drupal doesn't have support for base64 image storage/retrieval/conversion. I imagine you'll need to download and save the file using standard php, and then simply link the downloaded file to a node through a new file entity referencing that file
    – Clive
    Oct 2, 2016 at 10:35
  • thanks for answer . i currently see only 1 way to save from base64 $file = file_save_data(base64_decode($data['data']));
    – Yurii K.
    Oct 2, 2016 at 10:41
  • Yep, sounds reasonable.
    – Clive
    Oct 2, 2016 at 10:42

1 Answer 1

3

my final solution was next:

$node = Node::load($data['case_id']);
$files = $node->field_case_file;
$dfSettings = $files->getDataDefinition()->getSettings();
$destination = $dfSettings['uri_scheme'].'://'.$dfSettings['file_directory'].'/'.$filename;
$destination = \Drupal::token()->replace($destination);
$file = file_save_data(base64_decode($fileData), $destination, FILE_EXISTS_RENAME);

$violations = $files->appendItem($file)->validate();

if(count($violations)) {
//throw error
}

$node->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.