0

Below is my 2 line code to get the Mime Type of an attachment in a preprocess function

$file = $node->get('field_attachment_file')->entity;
$variables['attach_type'] = $file->getMimeType();

The $variables['attach_type'] is always getting the value of 'application/pdf' despite the attachment being an Microsoft Excel spreadsheet

  • 1
    Is the file extension correct? If the filename is example.xlsx.pdf, it would think it is a PDF file. – kiamlaluno Mar 7 at 5:09
  • yes the file extension is correct. It's example.xlsx – NKP Mar 13 at 2:47
2

The value returned as MIME type of a file is the value returned from the file.mime_type.guesser service which, on a default Drupal installation, uses three classes to guess the MIME type:

It is also possible that a module implements hook_file_mimetype_mapping_alter() to change the value returned from the first class, the file used from file or fileinfo_file() contains the wrong values, or another module implements another guesser class that is used before the other classes and returns the wrong MIME type.

  • So is it safe to assume it's an issue with core? – NKP Mar 13 at 2:48
  • Office 2007 File Format MIME Types for HTTP Content Streaming suggests that the correct MIME type for .xlsx files should be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. The Drupal core issue is not having an explicit mapping for those files. I cannot say you get application/pdf because a core bug. – kiamlaluno Mar 13 at 7:58

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.