【问题标题】:Laravel 5 - get MIME type from file extensionLaravel 5 - 从文件扩展名中获取 MIME 类型
【发布时间】:2015-06-13 02:57:56
【问题描述】:

在 Laravel 5 中,我如何从扩展中获取 MIME 类型?如果有办法将扩展数组转换为哑剧数组,那就更好了。

例如如何将array('doc', 'xls') 转换为array('application/msword', 'application/vnd.ms-excel')

【问题讨论】:

标签: php laravel laravel-5 mime


【解决方案1】:

首先,您需要下载这个公共域文件:http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

然后使用下面的函数读取文件,得到一个扩展名对应的MIME类型:

function getMIME($extension) {
    $file = "mime.types";
    $in = fopen($file, "r");
    while (($line = fgets($in)) !== false) {
        if (preg_match("/([a-z]+\/[a-z]+)\s+([a-z\s]*)\b($extension)\b/", $line, $match)) {
            return $match[1];
        }
    }
    fclose($in);
    return "error";
}

echo getMIME("doc");

输出:

应用程序/msword

要转换数组:

$myArray = array('doc', 'xls');

foreach($myArray as $key => $value){
    $myArray[$key] = getMIME($value);
}

【讨论】:

    【解决方案2】:

    Guzzle 默认包含在 Laravel 5 中,这个库中有 list of mime typesfromExtension() 方法,它们完全符合要求。

    所以,要获得单个扩展的 MIME 类型:

    $mimetypes = new \GuzzleHttp\Mimetypes;
    
    $mime = $mimetypes->fromExtension($extension);
    

    从扩展数组中获取 MIME 类型数组:

    $mimetypes = new \GuzzleHttp\Mimetypes;
    
    $mimes = [];
    foreach ($extensions as $extension) {
        $mimes[] = $mimetypes->fromExtension($extension);
    }
    

    【讨论】:

    • 仅供参考,截至 Guzzle 6.0 GuzzleHttp\Mimetypes 已移至 GuzzleHttp\Psr7\mimetype_from_extensionGuzzleHttp\Psr7\mimetype_from_filename 中的函数
    【解决方案3】:

    当 "guzzlehttp/guzzle": "~5.3|~6.0" 在你的 composer.json 中时,你可以使用这个:

    $mimetype = \GuzzleHttp\Psr7\mimetype_from_filename('foo.doc');
    $mimetype = \GuzzleHttp\Psr7\mimetype_from_extension('doc');
    

    【讨论】:

    • 来自函数phpdoc:@deprecated mimetype_from_filename will be removed in guzzlehttp/psr7:2.0. Use MimeType::fromFilename instead.
    【解决方案4】:

    简直就是 L5 中的佼佼者:

    \File::mimeType('physical/path/to/file.ext');
    

    【讨论】:

      【解决方案5】:
      MimeType::from('koala_transparent.png')
      

      返回“图片/png”

      【讨论】:

        【解决方案6】:

        我用过

        https://github.com/ralouphie/mimey

        它可以通过扩展名提供mimetype没有现有文件

        【讨论】:

          【解决方案7】:

          获取文件mimetype

          $request->file->getMimeType()
          

          验证码

          $request->validate([
              'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg'
              'mp3'=>'required|mimetypes:audio/mpeg'
             ]);
          

          您可以从上面的代码中获取文件类型,之后您可以将其设置为 mimetypes,就像为 mp3 设置的那样

          【讨论】:

            猜你喜欢
            • 2010-11-05
            • 2013-11-10
            • 2013-09-11
            • 2014-06-14
            • 1970-01-01
            • 2011-05-27
            • 2019-09-24
            相关资源
            最近更新 更多