当前位置: 首页>>代码示例>>PHP>>正文


PHP FileHelper::getExtensionsByMimeType方法代码示例

本文整理汇总了PHP中yii\helpers\FileHelper::getExtensionsByMimeType方法的典型用法代码示例。如果您正苦于以下问题:PHP FileHelper::getExtensionsByMimeType方法的具体用法?PHP FileHelper::getExtensionsByMimeType怎么用?PHP FileHelper::getExtensionsByMimeType使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在yii\helpers\FileHelper的用法示例。


在下文中一共展示了FileHelper::getExtensionsByMimeType方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: determineExtension

 /**
  * @param $content
  *
  * @return mixed
  * @throws \yii\base\InvalidConfigException
  */
 protected function determineExtension($content)
 {
     $filename = \Yii::getAlias('@runtime/' . uniqid());
     file_put_contents($filename, $content);
     $mime = FileHelper::getMimeType($filename);
     $extensions = FileHelper::getExtensionsByMimeType($mime);
     unlink($filename);
     return ArrayHelper::getValue($extensions, max(count($extensions) - 1, 0));
 }
开发者ID:voodoo-mobile,项目名称:yii2-upload,代码行数:15,代码来源:Writer.php

示例2: getExtension

 /**
  * @inheritdoc
  */
 public function getExtension()
 {
     // Generate the extension based on the MIME type if possible, eliminates inconsistencies
     $mimeType = end(FileHelper::getExtensionsByMimeType($this->getType()));
     // Fallback on the file extension
     if ($mimeType === false) {
         $mimeType = substr($this->uri, strrpos($this->uri, '.') + 1);
     }
     return $mimeType;
 }
开发者ID:nordsoftware,项目名称:yii2-file-manager,代码行数:13,代码来源:FileResource.php

示例3: generateName

 /**
  * @return null|string
  */
 function generateName()
 {
     if (!file_exists($this->tmp_name)) {
         return null;
     }
     $finfo = new finfo(FILEINFO_MIME_TYPE);
     $extension = FileHelper::getExtensionsByMimeType($finfo->buffer(file_get_contents($this->tmp_name, FILEINFO_MIME_TYPE)));
     $extension = empty($extension) ? '' : $extension[0];
     $hash = sha1_file($this->tmp_name);
     return "{$hash}.{$this->size}.{$extension}";
 }
开发者ID:nfilin,项目名称:yii2-libs,代码行数:14,代码来源:File.php

示例4: validateExtension

 /**
  * Checks if given uploaded file have correct type (extension) according current validator settings.
  * @param UploadedFile $file
  * @return boolean
  */
 protected function validateExtension($file)
 {
     $extension = mb_strtolower($file->extension, 'utf-8');
     if ($this->checkExtensionByMimeType) {
         $mimeType = FileHelper::getMimeType($file->tempName, null, false);
         if ($mimeType === null) {
             return false;
         }
         $extensionsByMimeType = FileHelper::getExtensionsByMimeType($mimeType);
         if (!in_array($extension, $extensionsByMimeType, true)) {
             return false;
         }
     }
     if (!in_array($extension, $this->extensions, true)) {
         return false;
     }
     return true;
 }
开发者ID:jenn0pal,项目名称:yii2,代码行数:23,代码来源:FileValidator.php

示例5: upload

 /**
  *
  * Загрузить файл в хранилище, добавить в базу, вернуть модель StorageFile
  *
  * @param UploadedFile|string|File $file    объект UploadedFile или File или rootPath до файла локально или http:// путь к файлу (TODO:: доделать)
  * @param array $data                       данные для сохранения в базу
  * @param null $clusterId                   идентификатор кластера по умолчанию будет выбран первый из конфигурации
  * @return StorageFile
  * @throws Exception
  */
 public function upload($file, $data = [], $clusterId = null)
 {
     //Для начала всегда загружаем файл во временную диррикторию
     $tmpdir = Dir::runtimeTmp();
     $tmpfile = $tmpdir->newFile();
     if ($file instanceof UploadedFile) {
         $extension = File::object($file->name)->getExtension();
         $tmpfile->setExtension($extension);
         if (!$file->saveAs($tmpfile->getPath())) {
             throw new Exception("Файл не загружен во временную диррикторию");
         }
     } else {
         if ($file instanceof File || is_string($file) && BaseUrl::isRelative($file)) {
             $file = File::object($file);
             $tmpfile->setExtension($file->getExtension());
             $tmpfile = $file->move($tmpfile);
         } else {
             if (is_string($file) && !BaseUrl::isRelative($file)) {
                 $curl_session = curl_init($file);
                 if (!$curl_session) {
                     throw new Exception("Неверная ссылка");
                 }
                 curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
                 curl_setopt($curl_session, CURLOPT_BINARYTRANSFER, true);
                 $file_content = curl_exec($curl_session);
                 curl_close($curl_session);
                 if (!$file_content) {
                     throw new Exception("Не удалось скачать файл");
                 }
                 $extension = pathinfo($file, PATHINFO_EXTENSION);
                 $pos = strpos($extension, "?");
                 if ($pos === false) {
                 } else {
                     $extension = substr($extension, 0, $pos);
                 }
                 if ($extension) {
                     $tmpfile->setExtension($extension);
                 }
                 $is_file_saved = file_put_contents($tmpfile, $file_content);
                 if (!$is_file_saved) {
                     throw new Exception("Не удалось сохранить файл");
                 }
                 //Если в ссылке нет расширения
                 if (!$extension) {
                     $tmpfile = new File($tmpfile->getPath());
                     try {
                         $mimeType = FileHelper::getMimeType($tmpfile->getPath(), null, false);
                     } catch (InvalidConfigException $e) {
                         throw new Exception("Не удалось пределить расширение файла: " . $e->getMessage());
                     }
                     if (!$mimeType) {
                         throw new Exception("Не удалось пределить расширение файла");
                     }
                     $extensions = FileHelper::getExtensionsByMimeType($mimeType);
                     if ($extensions) {
                         if (in_array("jpg", $extensions)) {
                             $extension = 'jpg';
                         } else {
                             if (in_array("png", $extensions)) {
                                 $extension = 'png';
                             } else {
                                 $extension = $extensions[0];
                             }
                         }
                         $newFile = new File($tmpfile->getPath());
                         $newFile->setExtension($extension);
                         $tmpfile = $tmpfile->copy($newFile);
                     }
                 }
             } else {
                 throw new Exception("Файл должен быть определен как \\yii\\web\\UploadedFile или \\skeeks\\sx\\File или string");
             }
         }
     }
     $data["type"] = $tmpfile->getType();
     $data["mime_type"] = $tmpfile->getMimeType();
     $data["size"] = $tmpfile->size()->getBytes();
     $data["extension"] = $tmpfile->getExtension();
     //Елси это изображение
     if ($tmpfile->getType() == 'image') {
         if (extension_loaded('gd')) {
             list($width, $height, $type, $attr) = getimagesize($tmpfile->toString());
             $data["image_height"] = $height;
             $data["image_width"] = $width;
         }
     }
     if ($cluster = $this->getCluster($clusterId)) {
         if ($newFileSrc = $cluster->upload($tmpfile)) {
             $data = array_merge($data, ["src" => $cluster->getPublicSrc($newFileSrc), "cluster_id" => $cluster->getId(), "cluster_file" => $newFileSrc]);
         }
//.........这里部分代码省略.........
开发者ID:Liv1020,项目名称:cms,代码行数:101,代码来源:Storage.php

示例6: getExtensionByMimeType

 public static function getExtensionByMimeType($mimeType)
 {
     $extensions = FileHelper::getExtensionsByMimeType($mimeType);
     if (empty($extensions)) {
         return false;
     }
     return mb_strtolower($extensions[0], 'utf-8');
 }
开发者ID:salopot,项目名称:yii2-attach-image,代码行数:8,代码来源:AttachFileBehavior.php

示例7: getExtensionByMimeType

 /**
  * @return mixed
  */
 public function getExtensionByMimeType()
 {
     $extensions = FileHelper::getExtensionsByMimeType($this->getMimeType());
     return array_shift($extensions);
 }
开发者ID:yiioverflow,项目名称:yii2-file-kit,代码行数:8,代码来源:File.php

示例8: getExtensionName

 /**
  * @param $body
  * @return array|null
  * @throws InvalidConfigException
  */
 protected static function getExtensionName($body)
 {
     if (@is_file($body)) {
         $info = getimagesize($body);
         if (empty($info)) {
             $mimeType = FileHelper::getMimeType($body);
             if ($mimeType && ($extensions = FileHelper::getExtensionsByMimeType($mimeType))) {
                 return $extensions ? current($extensions) : null;
             }
         } else {
             $mimeType = $info[2];
             return image_type_to_extension($mimeType, false);
         }
     } elseif ($info = getimagesizefromstring($body)) {
         $mimeType = $info[2];
         return image_type_to_extension($mimeType, false);
     }
     return null;
 }
开发者ID:cdcchen,项目名称:yii2-cloud-storage,代码行数:24,代码来源:UpYunStorage.php

示例9: upload

 /**
  * Upload file
  * @param \yii\web\UploadedFile $file
  * @return bool
  */
 public function upload($file)
 {
     if (is_string($file)) {
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $file);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
         $content = curl_exec($ch);
         $info = curl_getinfo($ch);
         if (curl_error($ch)) {
             return false;
         }
         curl_close($ch);
         if ($info['http_code'] != 200) {
             return false;
         }
         $tempName = tempnam(sys_get_temp_dir(), 'php');
         $tempHandle = fopen($tempName, 'w');
         fwrite($tempHandle, $content);
         fclose($tempHandle);
         $arr = explode('/', $file);
         $fileName = explode('?', end($arr))[0];
         $this->model->size = filesize($tempName);
         $this->model->content_type = mime_content_type($tempName);
         $types = FileHelper::getExtensionsByMimeType($this->model->content_type);
         $this->model->ext = end($types);
         $this->model->file_name = $fileName ? $fileName : 'unnamed.' . $this->model->ext;
     } elseif ($file instanceof \yii\web\UploadedFile) {
         $tempName = $file->tempName;
         $this->model->size = $file->size;
         $this->model->file_name = $file->name;
         $this->model->content_type = $file->type;
         $this->model->ext = $file->extension;
     } else {
         return false;
     }
     if (($imageInfo = getimagesize($tempName)) !== false) {
         $this->model->width = $imageInfo[0];
         $this->model->height = $imageInfo[1];
         $this->model->is_image = true;
     }
     $this->model->code = md5(time() . implode('', $this->model->attributes));
     if (!$this->model->save()) {
         return false;
     }
     $dir = $this->dir . '/' . $this->model->id . '/';
     FileHelper::createDirectory($dir);
     $original = $dir . 'original.' . $this->model->ext;
     if (is_string($file)) {
         @rename($tempName, $original);
     } else {
         if (!$file->saveAs($original)) {
             return false;
         }
     }
     if ($fp = fopen($dir . $this->model->code . '.txt', 'w')) {
         fclose($fp);
     } else {
         return false;
     }
     return true;
 }
开发者ID:sersid,项目名称:yii2-file-upload,代码行数:68,代码来源:File.php

示例10: upload

 public static function upload($file, $name = null, $dir = self::F_FILES, $slug = null, $data = null, $delete = true)
 {
     if (is_null($dir)) {
         $dir = self::F_FILES;
     }
     $dir = trim($dir);
     $filePath = '';
     if (strpos($file, 'http') === 0) {
         $tmp = Yii::getAlias('@runtime') . DIRECTORY_SEPARATOR . uniqid("fu");
         file_put_contents($tmp, file_get_contents($file));
         $filePath = $tmp;
         $name = $name ? $name : basename($file);
     } elseif (is_string($file)) {
         $filePath = Yii::getAlias($file);
     } elseif ($file instanceof UploadedFile) {
         $filePath = $file->tempName;
         $name = $name ? $name : $file->name;
     }
     $name = $name ? $name : basename($filePath);
     $sec = new Security();
     while (FileUpload::find()->where(["path" => $uniquePath = md5($sec->generateRandomString())])->one()) {
     }
     $dirSlug = $dir;
     if (!is_dir($dir) && !($dir = self::getFolder($dirSlug))) {
         if (!$dir) {
             throw new \Exception("Folder for param '{$dirSlug}' is not set");
         } else {
             throw new \Exception("Folder '{$dir}' not found");
         }
     }
     $fullPath = self::formPath($uniquePath, $dir);
     if (!FileHelper::createDirectory(dirname($fullPath))) {
         throw new \Exception("Can't create folder '{" . dirname($fullPath) . "}'");
     }
     if (!file_exists($filePath)) {
         throw new \Exception('File not loaded or not exist');
     }
     if (is_uploaded_file($filePath)) {
         if (!move_uploaded_file($filePath, $fullPath)) {
             throw new \Exception('Unknown upload error');
         }
     } elseif ($delete ? !rename($filePath, $fullPath) : !copy($filePath, $fullPath)) {
         throw new \Exception('Failed to write file to disk');
     }
     $info = pathinfo($name);
     $fileUpload = new self();
     //Фиск для сессии, при аяксовом запросе
     if (isset(Yii::$app->session)) {
         Yii::$app->session->open();
         $fileUpload->session = Yii::$app->session->getIsActive() ? Yii::$app->session->getId() : null;
         Yii::$app->session->close();
     }
     $fileUpload->user_id = CurrentUser::getId(1);
     $fileUpload->data = !is_null($data) ? json_encode($data) : null;
     $fileUpload->mime_type = FileHelper::getMimeType($fullPath);
     $fileUpload->md5 = md5_file($fullPath);
     $fileUpload->folder = $dirSlug;
     $fileUpload->path = $uniquePath;
     $fileUpload->slug = $slug;
     $fileUpload->size = filesize($fullPath);
     if (!($extension = strtolower(ArrayHelper::getValue($info, "extension")))) {
         $extension = ArrayHelper::getValue(FileHelper::getExtensionsByMimeType($fileUpload->mime_type), 0);
     }
     $fileUpload->name = basename($name, '.' . $extension);
     $fileUpload->extension = $extension;
     if ($fileUpload->save()) {
         return $fileUpload;
     } else {
         $fileUpload->deleteFile();
         return null;
     }
 }
开发者ID:carono,项目名称:yii2-components,代码行数:72,代码来源:FileUpload.php


注:本文中的yii\helpers\FileHelper::getExtensionsByMimeType方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。