【问题标题】:Symfony : How to get right mime type on ppt and pptxSymfony:如何在 ppt 和 pptx 上获得正确的 mime 类型
【发布时间】:2020-01-20 15:40:13
【问题描述】:

我想将一个 PowerPoint 文件导入我的 Symfony 应用程序。 我允许这些 mime 类型进入白名单参数。

co_upload_white_list: 
    - "image/*"
    - "application/pdf"
    - "application/x-pdf"
    - "application/msword"
    - "application/vnd.openxmlformats-officedocument.presentationml.presentation"
    - "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    - "application/vnd.oasis.opendocument.text"
    - "application/vnd.ms-excel"
    - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    - "application/vnd.oasis.opendocument.spreadsheet"
    - "application/vnd.ms-powerpoint"

此代码工作正常,但 Symfony/Component/HttpFoundation/File/MimeType/FileBinaryMimeTypeGuesser.php 在 $file->getMimeType() 处返回的 mimetype : application / octet-stream 但它应该是 application/vnd.openxmlformats-officedocument .presentationml.presentation

use Oneup\UploaderBundle\Uploader\Naming\NamerInterface;

class UploadListener implements NamerInterface
{
[....]

    public function onValidate(ValidationEvent $event)
    {

     /**
     * $file is oneup/uploader-bundle/Uploader/File/FilesystemFile.php
     */
    $file = $event->getFile();
    $mimeType = $file->getMimeType();
    $fileSize = $file->getSize();
    $ext = $file->getExtension();

    $hotel = $event->getRequest()->attributes->get('hotel');
    $locale = ($hotel->getUserLocale()) ? $hotel->getUserLocale() : 'en';

    if (explode("/", $mimeType)[0] != "image" && !in_array($mimeType, $this->uploadWhiteList)) {

        $this->messenger->error("MimeType invalid: %mimeType%", ['%mimeType%' => $mimeType], $locale);
        throw new HttpException(400, "File type invalid, mimetype is '$mimeType', allowed=".json_encode($this->uploadWhiteList));
    }
[...]
}

有没有办法获得正确的 mime 类型?

【问题讨论】:

    标签: symfony mime-types


    【解决方案1】:

    尝试使用mime_content_type

    echo mime_content_type("example.ppt");
    

    输出:

    应用程序/vnd.ms-powerpoint

    Try this

    使用 symfony 这对我有用(symfony 3.4);

        $filepath = "/tmp/example.ppt";
        file_put_contents($filepath, file_get_contents("https://sample-videos.com/ppt/Sample-PPT-File-500kb.ppt"));
        $file = new \Symfony\Component\HttpFoundation\File\File($filepath);
        echo $file->getMimeType();
    

    同样的输出:

    应用程序/vnd.ms-powerpoint

    【讨论】:

    • 谢谢。我将完成我的代码,我从 ValidationEvent 取回 $event。我的课程是事件监听 - { name: "kernel.event_listener", event: "oneup_uploader.validation", method: "onValidate" }
    • 添加:$file 是一个扩展 UploadedFile 并实现 FileInterface 的 oneup/uploader-bundle/Uploader/File/FilesystemFile.php。并且 getMimeType() 返回 application/octetStream
    猜你喜欢
    • 2011-05-11
    • 2017-03-28
    • 1970-01-01
    相关资源
    最近更新 更多