0

I am receiving a payload with blob files.

I would like to store them as files and create a media entity.

Here's the code I have to create the Media object

 if (!empty($payload['blobFile'])) {
  $name = str_replace(' ', '_', $payload['fileName']);
  $file = file_save_data($payload['blobFile'], 'public://' . $name, FILE_EXISTS_REPLACE);
  $content['field_media_file'] = ['target_id' => $file->id()];
}
$this->entityTypeManager->getStorage(....

It successfully creates the media content and attach a file to it.

Unfortunately the file is still blob I don't see a pdf or similar.

  • 2
    I think that you mean "blob" as in a Blob as part of the Web API, and that you are receiving some raw binary data as the payload, but this is not particularly clear. If you could clarify what "blob" means one way or another that might help. If the Blob is encoded, say in base64, perhaps you need to decode it prior to saving it? – mradcliffe Dec 10 '19 at 23:03
  • Hi mradcliffe, thank you. I have already solved it by adding base64_decode. But as you answered correctly, please put it in a comment s I can accept it. – Tyler Durden Dec 11 '19 at 16:51
  • Sorry, I didn't get back to this for so long. – mradcliffe Jan 13 at 13:09
2

A file that comes in from a browser's Web API as a Blob is probably base64-encoded. PHP will not decode files in the POST or GET parameters. It is up to the PHP application to decode the file before saving.

if (!empty($payload['blobFile'])) {
  $name = str_replace(' ', '_', $payload['fileName']);
  $file = file_save_data(base64_decode($payload['blobFile']), 'public://' . $name, FILE_EXISTS_REPLACE);
  $content['field_media_file'] = ['target_id' => $file->id()];
}

It might also be useful to check if the binary is actually a PDF before saving, but that could be done in different ways based on opinion (loading via a PDF library, checking file headers, virus/malware scan).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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