如何获取要下载的文件的MIME类型? [英] How to get MIME Type of a file to be downloaded?
问题描述
我必须通过点击链接下载列出的文件,因为我使用了下面的脚本,但是当文件被下载时,它不能识别下载文件的扩展名。那么,如何获取要下载的文件的MIME类型? _请求帮助...
I Have to download the listed file on click of the link, for whic I have used the below scripot, but I when the file gets dowloaded, it cannot idenetify the extension of downloaded file. So, How to get MIME Type of a file to be downloaded? _Please Help...
$filename = $_GET['val'];
// Fetch the file info.
$filePath = $_SERVER['DOCUMENT_ROOT'] . "dfms/images/uploads/".$filename;
if(file_exists($filePath)) {
echo $fileName = basename($filePath);
$fileSize = filesize($filePath);
// Output headers.
header("Cache-Control: private");
header("Content-Type: application/octet");
header("Content-Length: ".$fileSize);
header("Content-Disposition: attachment; filename=".$fileName);
// Output file.
readfile ($filePath);
exit();
}
else {
die('The provided file path is not valid.');
}
推荐答案
使用finfo_file函数FileInfo扩展名(PHP 5.3中默认启用)。
http://www.php.net/manual/en /function.finfo-file.php
Using the finfo_file function from the FileInfo extension (enabled by default in PHP 5.3). http://www.php.net/manual/en/function.finfo-file.php
从文档中的示例
$finfo = finfo_open(FILEINFO_MIME_TYPE);
echo finfo_file($finfo, $filename);
finfo_close($finfo);
在5.3之前的PHP版本中,可以安装pecl扩展名 http://pecl.php.net/package/Fileinfo
In PHP versions prior to 5.3 the pecl extension can be installed http://pecl.php.net/package/Fileinfo
然而在在这种情况下,它需要magic_open(libmagic)库 http://sourceforge.net/projects/libmagic
However in this case it requires the magic_open (libmagic) library http://sourceforge.net/projects/libmagic
另一种方法是使用不推荐的函数 mime_content_type($ filename)
http://au.php.net/manual/en/function.mime-content-type.php
The alternative is to use the deprecated function mime_content_type($filename)
http://au.php.net/manual/en/function.mime-content-type.php
哪个依赖于mime.magic文件
Which relies on the mime.magic file
这篇关于如何获取要下载的文件的MIME类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!