0

I wrote a module to strip Exif data from uploaded file.

function modulename_file_presave(Drupal\file\FileInterface $file) {
if ($file->getMimeType() == 'image/jpeg') {
  $filepath = \Drupal::service('file_system')->realpath($file->getFileUri());
  $path = $file->getFileUri();
  $img = new Imagick($path);
  $img->stripImage();
  $img->writeImage($filepath);
  $img->clear;
}

it works to all files, but I want to restrict this module to work in only specific content type. How can I get the content type in my module? Thank you.

1

The file itself has no reference to the parent node (it can be referenced by multiple entities). But you can get the node type you are adding or the node you are editing when you upload the file from the route:

function modulename_file_presave(\Drupal\file\FileInterface $file) {
  if ($file->getMimeType() == 'image/jpeg') {
    switch (\Drupal::routeMatch()->getRouteName()) {
      case 'node.add':
        $content_type = \Drupal::routeMatch()->getRawParameter('node_type');
        break;

      case 'entity.node.edit_form':
        $node = \Drupal::routeMatch()->getParameter('node');
        $content_type = $node->getType();
        break;

      default:
        $content_type = NULL;
    }
  }
}
0

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.