本文整理汇总了PHP中yii\helpers\FileHelper::getMimeTypeByExtension方法的典型用法代码示例。如果您正苦于以下问题:PHP FileHelper::getMimeTypeByExtension方法的具体用法?PHP FileHelper::getMimeTypeByExtension怎么用?PHP FileHelper::getMimeTypeByExtension使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yii\helpers\FileHelper
的用法示例。
在下文中一共展示了FileHelper::getMimeTypeByExtension方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: actionDownloadZippedFolder
/**
* Action to download a folder defined by request param "fid" as a zip file.
*
* @throws HttpException
*/
public function actionDownloadZippedFolder()
{
// cleanup all old files
$this->cleanup();
// init output directory
$outputPath = $this->getZipOutputPath();
// check validity of currentFolder
$currentFolder = $this->getCurrentFolder();
if (empty($currentFolder)) {
throw new HttpException(404, Yii::t('CfilesModule.base', 'The folder with the id %id% does not exist.', ['%id%' => (int) Yii::$app->request->get('fid')]));
}
// zip the current folder
$zipTitle = $this->zipDir($currentFolder, $outputPath);
$zipPath = $outputPath . DIRECTORY_SEPARATOR . $zipTitle;
// check if the zip was created
if (!file_exists($zipPath)) {
throw new HttpException(404, Yii::t('CfilesModule.base', 'The archive could not be created.'));
}
// deliver the zip
$options = ['inline' => false, 'mimeType' => FileHelper::getMimeTypeByExtension($zipPath)];
if (!Setting::Get('useXSendfile', 'file')) {
Yii::$app->response->sendFile($zipPath, $zipTitle, $options);
} else {
if (strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') === 0) {
// set nginx specific X-Sendfile header name
$options['xHeader'] = 'X-Accel-Redirect';
// make path relative to docroot
$docroot = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR);
if (substr($zipPath, 0, strlen($docroot)) == $docroot) {
$zipPath = substr($zipPath, strlen($docroot));
}
}
Yii::$app->response->xSendFile($zipPath, null, $options);
}
}
示例2: run
public function run($url = null)
{
/**
* @var ImageCache $imageCache
*/
$imageCache = Yii::$app->get('imageCache');
$cachedUrl = $url ?: Yii::$app->request->getUrl();
$preg = '/^' . preg_quote(Yii::getAlias($imageCache->cacheUrl), '/') . '\\/(.*?)\\/(.*?)\\.(.*?)$/';
if (preg_match($preg, $cachedUrl, $matches)) {
$presetName = $matches[1];
$imagePath = Yii::getAlias($imageCache->staticPath . DIRECTORY_SEPARATOR . $matches[2] . '.' . $matches[3]);
$format = strtolower($matches[3]);
if (file_exists($imagePath)) {
try {
$image = $imageCache->getImage($imagePath, $presetName);
if ($image && $image->isValid()) {
if ($imageCache->actionSavesFile) {
$cachedPath = Yii::getAlias($imageCache->cachePath . DIRECTORY_SEPARATOR . $presetName . DIRECTORY_SEPARATOR . $matches[2] . '.' . $matches[3]);
//var_dump($cachedPath);
FileHelper::createDirectory(dirname($cachedPath));
$image->save($cachedPath);
}
Yii::$app->response->format = Response::FORMAT_RAW;
Yii::$app->getResponse()->getHeaders()->set('Pragma', 'public')->set('Expires', '0')->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')->set('Content-Transfer-Encoding', 'binary')->set('Content-type', FileHelper::getMimeTypeByExtension($imagePath));
return $image->get($format);
}
} catch (\Exception $e) {
throw new BadRequestHttpException();
}
} else {
throw new NotFoundHttpException();
}
}
throw new BadRequestHttpException('Wrong url format!');
}
示例3: printFile
public function printFile($file)
{
Yii::$app->response->format = Response::FORMAT_RAW;
header("Expires: " . gmdate('r', time() + 60 * 60 * 24 * 30));
header("Last-Modified: " . gmdate('r'));
header('Content-Type: ' . FileHelper::getMimeTypeByExtension($file, FileHelper::$mimeMagicFile));
header("Content-Length: " . filesize($file));
readfile($file);
}
示例4: run
public function run()
{
/* @var $request \yii\web\Request */
/* @var $response \yii\web\Response */
$request = Yii::$app->request;
$response = Yii::$app->response;
$reportName = $request->getQueryParam('name', $this->name);
$outputType = $request->getQueryParam('outputType', $this->outputType);
$params = $request->getQueryParam('params', []);
$return = $this->report->renderReport($reportName, ['params' => $params], $outputType);
if ($outputType != BirtReport::OUTPUT_TYPE_HTML) {
$response->format = Response::FORMAT_RAW;
$fileName = explode('.', $reportName, 1)[0] . '.' . $outputType;
$mimeType = \yii\helpers\FileHelper::getMimeTypeByExtension($fileName);
$response->setDownloadHeaders($fileName, $mimeType);
}
return $return;
}
示例5: validateExtension
public function validateExtension($attribute, $params)
{
$file = $this->{$attribute};
$pathinfo = pathinfo(mb_strtolower($file->name, 'utf-8'));
if (!empty($pathinfo['extension'])) {
$extension = $pathinfo['extension'];
} else {
return false;
}
if ($this->checkExtensionByMimeType) {
$mimeType = FileHelper::getMimeType($file->tempName, null, false);
if ($mimeType === null) {
return false;
}
if (!FileHelper::getMimeTypeByExtension($file)) {
return false;
}
}
if (!in_array($extension, $this->extensions, true)) {
return false;
}
return true;
}
示例6: actionUpload
/**
* @return string
*/
public function actionUpload()
{
$magic = new Magic(['scenario' => 'many']);
$magic->load(Yii::$app->request->post());
$magic->files = UploadedFile::getInstances($magic, 'files');
if ($magic->validate()) {
foreach ($magic->files as $file) {
$model = new Magic(['scenario' => 'one']);
$model->load(Yii::$app->request->post());
$model->file = $file;
$model->label = StringHelper::basename($model->file->name, '.' . $model->file->extension);
$model->mime = FileHelper::getMimeTypeByExtension($model->file);
$model->setSrc();
$model->file->saveAs($model->getSrcPath());
if ($model->getType() == 'image') {
$model->setPreview();
Image::thumbnail($model->getSrcPath(), Magic::PREVIEW_WIDTH, Magic::PREVIEW_HEIGHT)->save($model->getPreviewPath(), ['quality' => 75]);
}
$model->save();
}
}
return $this->display($magic);
}
示例7: download
/**
* Download file from PHPWord instance
* @param PHPWord $phpWord reference to phpWord
* @param string $fileName file name
* @param string $format file save format
*/
public function download(PHPWord &$phpWord, $fileName, $format = 'Word2007')
{
if (!in_array($format, array_keys(static::$map))) {
$format = $this->defaultFormat;
}
$fileName .= '.' . static::$map[$format];
header('Content-Type: ' . FileHelper::getMimeTypeByExtension($fileName));
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
// If you're serving to IE 9, then the following may be needed
// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
// Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
// always modified
header('Cache-Control: cache, must-revalidate');
// HTTP/1.1
header('Pragma: public');
// HTTP/1.0
$writer = IOFactory::createWriter($phpWord, $format);
$writer->save('php://output');
Yii::$app->end();
}
示例8: actionDownload
/**
* Downloads a file
*/
public function actionDownload()
{
// GUID of file
$guid = Yii::$app->request->get('guid');
// Force Download Flag
$download = Yii::$app->request->get('download', 0);
// Optional suffix of file (e.g. scaled variant of image)
$suffix = Yii::$app->request->get('suffix');
$file = File::findOne(['guid' => $guid]);
if ($file == null) {
throw new HttpException(404, Yii::t('FileModule.controllers_FileController', 'Could not find requested file!'));
}
if (!$file->canRead()) {
throw new HttpException(401, Yii::t('FileModule.controllers_FileController', 'Insufficient permissions!'));
}
$filePath = $file->getPath();
$fileName = $file->getFilename($suffix);
if (!file_exists($filePath . DIRECTORY_SEPARATOR . $fileName)) {
throw new HttpException(404, Yii::t('FileModule.controllers_FileController', 'Could not find requested file!'));
}
$options = ['inline' => false, 'mimeType' => FileHelper::getMimeTypeByExtension($fileName)];
if ($download != 1 && in_array($options['mimeType'], Yii::$app->getModule('file')->inlineMimeTypes)) {
$options['inline'] = true;
}
if (!Setting::Get('useXSendfile', 'file')) {
Yii::$app->response->sendFile($filePath . DIRECTORY_SEPARATOR . $fileName, $fileName, $options);
} else {
if (strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') === 0) {
// set nginx specific X-Sendfile header name
$options['xHeader'] = 'X-Accel-Redirect';
// make path relative to docroot
$docroot = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR);
if (substr($filePath, 0, strlen($docroot)) == $docroot) {
$filePath = substr($filePath, strlen($docroot));
}
}
Yii::$app->response->xSendFile($filePath . DIRECTORY_SEPARATOR . $fileName, null, $options);
}
}
示例9: xSendFile
/**
* Sends existing file to a browser as a download using x-sendfile.
*
* X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
* that in turn processes the request, this way eliminating the need to perform tasks like reading the file
* and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
* increase in performance as the web application is allowed to terminate earlier while the webserver is
* handling the request.
*
* The request is sent to the server through a special non-standard HTTP-header.
* When the web server encounters the presence of such header it will discard all output and send the file
* specified by that header using web server internals including all optimizations like caching-headers.
*
* As this header directive is non-standard different directives exists for different web servers applications:
*
* - Apache: [X-Sendfile](http://tn123.org/mod_xsendfile)
* - Lighttpd v1.4: [X-LIGHTTPD-send-file](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
* - Lighttpd v1.5: [X-Sendfile](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
* - Nginx: [X-Accel-Redirect](http://wiki.nginx.org/XSendfile)
* - Cherokee: [X-Sendfile and X-Accel-Redirect](http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile)
*
* So for this method to work the X-SENDFILE option/module should be enabled by the web server and
* a proper xHeader should be sent.
*
* **Note**
*
* This option allows to download files that are not under web folders, and even files that are otherwise protected
* (deny from all) like `.htaccess`.
*
* **Side effects**
*
* If this option is disabled by the web server, when this method is called a download configuration dialog
* will open but the downloaded file will have 0 bytes.
*
* **Known issues**
*
* There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
* an error message like this: "Internet Explorer was not able to open this Internet site. The requested site
* is either unavailable or cannot be found.". You can work around this problem by removing the `Pragma`-header.
*
* **Example**
*
* ```php
* Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');
* ```
*
* @param string $filePath file name with full path
* @param string $attachmentName file name shown to the user. If null, it will be determined from `$filePath`.
* @param array $options additional options for sending the file. The following options are supported:
*
* - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
* - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
* meaning a download dialog will pop up.
* - xHeader: string, the name of the x-sendfile header. Defaults to "X-Sendfile".
*
* @return $this the response object itself
* @see sendFile()
*/
public function xSendFile($filePath, $attachmentName = null, $options = [])
{
if ($attachmentName === null) {
$attachmentName = basename($filePath);
}
if (isset($options['mimeType'])) {
$mimeType = $options['mimeType'];
} elseif (($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
$mimeType = 'application/octet-stream';
}
if (isset($options['xHeader'])) {
$xHeader = $options['xHeader'];
} else {
$xHeader = 'X-Sendfile';
}
$disposition = empty($options['inline']) ? 'attachment' : 'inline';
$this->getHeaders()->setDefault($xHeader, $filePath)->setDefault('Content-Type', $mimeType)->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
$this->format = self::FORMAT_RAW;
return $this;
}
示例10: getImportedMime
/**
* Returns MIME of the file
* @return string
*/
public function getImportedMime()
{
return FileHelper::getMimeTypeByExtension($this->file->name);
}
示例11: extendOptions
protected static function extendOptions(array $options)
{
$parsed_url = parse_url($options['url']);
$headers = @get_headers($options['url'], 1);
if (!$parsed_url || !$headers || !preg_match('/^(HTTP)(.*)(200)(.*)/i', $headers[0])) {
$options['error'] = UPLOAD_ERR_NO_FILE;
}
$fname = explode('/', $parsed_url['path']);
$options['name'] = end($fname);
$options['baseName'] = explode('.', $options['name'], 1);
$ext = explode('.', $options['name']);
$options['extension'] = mb_strtolower(end($ext));
$options['size'] = isset($headers['Content-Length']) ? $headers['Content-Length'] : 0;
$options['type'] = isset($headers['Content-Type']) ? $headers['Content-Type'] : FileHelper::getMimeTypeByExtension($options['name']);
return $options;
}
示例12: actionDownloadArchive
/**
* Action to download a zip of the selected items.
*
* @return Ambigous <\humhub\modules\cfiles\controllers\type, string>
*/
public function actionDownloadArchive()
{
if (Setting::Get('disableZipSupport', 'cfiles')) {
throw new HttpException(404, Yii::t('CfilesModule.base', 'Archive (zip) support is not enabled.'));
}
$selectedItems = Yii::$app->request->post('selected');
$items = [];
// download selected items if there are some
if (is_array($selectedItems)) {
foreach ($selectedItems as $itemId) {
$item = $this->module->getItemById($itemId);
if ($item !== null) {
$items[] = $item;
}
}
} else {
// check validity of currentFolder
$items = $this->getCurrentFolder();
if (empty($items)) {
throw new HttpException(404, Yii::t('CfilesModule.base', 'The folder with the id %id% does not exist.', ['%id%' => (int) Yii::$app->request->get('fid')]));
}
}
// cleanup all old files
$this->cleanup();
// init output directory
$outputPath = $this->getZipOutputPath();
$zipTitle = $this->archive($items, $outputPath);
$zipPath = $outputPath . DIRECTORY_SEPARATOR . $zipTitle;
// check if the zip was created
if (!file_exists($zipPath)) {
throw new HttpException(500, Yii::t('CfilesModule.base', 'The archive could not be created.'));
}
// deliver the zip
$options = ['inline' => false, 'mimeType' => FileHelper::getMimeTypeByExtension($zipPath)];
if (!Setting::Get('useXSendfile', 'file')) {
Yii::$app->response->sendFile($zipPath, $zipTitle, $options);
} else {
if (strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') === 0) {
// set nginx specific X-Sendfile header name
$options['xHeader'] = 'X-Accel-Redirect';
// make path relative to docroot
$docroot = rtrim($_SERVER['DOCUMENT_ROOT'], DIRECTORY_SEPARATOR);
if (substr($zipPath, 0, strlen($docroot)) == $docroot) {
$zipPath = substr($zipPath, strlen($docroot));
}
}
Yii::$app->response->xSendFile($zipPath, null, $options);
}
}
示例13: xSendFile
/**
* Sends existing file to a browser as a download using x-sendfile.
*
* X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
* that in turn processes the request, this way eliminating the need to perform tasks like reading the file
* and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
* increase in performance as the web application is allowed to terminate earlier while the webserver is
* handling the request.
*
* The request is sent to the server through a special non-standard HTTP-header.
* When the web server encounters the presence of such header it will discard all output and send the file
* specified by that header using web server internals including all optimizations like caching-headers.
*
* As this header directive is non-standard different directives exists for different web servers applications:
*
* - Apache: [X-Sendfile](http://tn123.org/mod_xsendfile)
* - Lighttpd v1.4: [X-LIGHTTPD-send-file](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
* - Lighttpd v1.5: [X-Sendfile](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
* - Nginx: [X-Accel-Redirect](http://wiki.nginx.org/XSendfile)
* - Cherokee: [X-Sendfile and X-Accel-Redirect](http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile)
*
* So for this method to work the X-SENDFILE option/module should be enabled by the web server and
* a proper xHeader should be sent.
*
* **Note**
*
* This option allows to download files that are not under web folders, and even files that are otherwise protected
* (deny from all) like `.htaccess`.
*
* **Side effects**
*
* If this option is disabled by the web server, when this method is called a download configuration dialog
* will open but the downloaded file will have 0 bytes.
*
* **Known issues**
*
* There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
* an error message like this: "Internet Explorer was not able to open this Internet site. The requested site
* is either unavailable or cannot be found.". You can work around this problem by removing the `Pragma`-header.
*
* **Example**
*
* ~~~
* Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');
* ~~~
*
* @param string $filePath file name with full path
* @param string $mimeType the MIME type of the file. If null, it will be determined based on `$filePath`.
* @param string $attachmentName file name shown to the user. If null, it will be determined from `$filePath`.
* @param string $xHeader the name of the x-sendfile header.
* @return static the response object itself
*/
public function xSendFile($filePath, $attachmentName = null, $mimeType = null, $xHeader = 'X-Sendfile')
{
if ($mimeType === null && ($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
$mimeType = 'application/octet-stream';
}
if ($attachmentName === null) {
$attachmentName = basename($filePath);
}
$this->getHeaders()->setDefault($xHeader, $filePath)->setDefault('Content-Type', $mimeType)->setDefault('Content-Disposition', "attachment; filename=\"{$attachmentName}\"");
return $this;
}
示例14: testGetMimeTypeByExtension
public function testGetMimeTypeByExtension()
{
$magicFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'mime_type.php';
$mimeTypeMap = ['txa' => 'application/json', 'txb' => 'another/mime'];
$magicFileContent = '<?php return ' . var_export($mimeTypeMap, true) . ';';
file_put_contents($magicFile, $magicFileContent);
foreach ($mimeTypeMap as $extension => $mimeType) {
$fileName = 'test.' . $extension;
$this->assertNull(FileHelper::getMimeTypeByExtension($fileName));
$this->assertEquals($mimeType, FileHelper::getMimeTypeByExtension($fileName, $magicFile));
}
}
示例15: setFile
/**
* Set model attributes from UploadedFile
* @param UploadedFile $file
* @return $this
*/
public function setFile(UploadedFile $file)
{
$this->file = $file;
$this->name = $file->name;
if ($this->unique === true && $file->extension) {
$this->setUriName(uniqid() . '.' . $file->extension);
} else {
$this->setUriName($this->name);
}
if (file_exists($this->filePath)) {
$this->setUriName($file->baseName . uniqid() . '.' . $file->extension);
}
$this->mime = FileHelper::getMimeTypeByExtension($this->name);
$this->size = $file->size;
return $this;
}