Score:0

How do you set the file extension while uploading images through file_save_data?

th flag

I am trying to create a product with a product image on drupal using API. I have created a custom module for the same under which following code to upload my image to the Drupal:

$path = base64_decode($encodedData['content']);
$data= $this->grabImage($path);
$file = file_save_data($data, null, FileSystemInterface::EXISTS_REPLACE);
        
$id = $file->id();

I am using file_save_data drupal method to upload the image successfully and it gets uploaded to the following drupal directory:

mystore2/web/sites/default/files

Now, I am using this $file->id() //say 53 value in my product array to connect this image to my product.

$image['field_picture'] = [[
    "target_id" => 53,
    "alt" => 'abcd',
    "width"=> 224,
    "height"=> 225,
    "title" => '',
    "target_type" => "file"
]];

Follow response I am receiving from API:

> message:
>     Unprocessable Entity: validation failed.
>     field_picture.0: Only files with the following extensions are allowed: png gif jpg jpeg.\n

So, How can I pass extension in file_save_data()? Or how can I add this image to my product?

I am using Drupal version ^9.

Score:0
cn flag

You need to pass the file path, including its name and extension, as the $destination parameter:

$file = file_save_data($data, 'public://path/to/file.ext', FileSystemInterface::EXISTS_REPLACE);
sonfd avatar
in flag
Where `path/to/file.ext` is whatever you'd like it to be (though you definitely want to be mindful if you're using the `FileSystemInterface::EXISTS_REPLACE` option).
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.