0

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.

1 Answer 1

0

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);
1
  • 1
    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).
    – sonfd
    Jul 20, 2021 at 15:07

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.