The mime type is guessed using the functions finfo(), mime_content_type()
and the system binary "file" (in this order), depending on which of those
is available on the current operating system.
public getMimeType ( ) : string | null | ||
return | string | null | The guessed mime type (i.e. "application/pdf") |
/** * Get mime type of file. * * @return string */ public function getMimeType() { if ($this->file instanceof UploadedFile) { return $this->file->getClientMimeType(); } return $this->file->getMimeType(); }
public function isValid($value, Constraint $constraint) { if (null === $value || '' === $value) { return true; } if (!is_scalar($value) && !$value instanceof FileObject && !(is_object($value) && method_exists($value, '__toString()'))) { throw new UnexpectedTypeException($value, 'string'); } if ($value instanceof FileObject && null === $value->getPath()) { return true; } $path = $value instanceof FileObject ? $value->getPath() : (string) $value; if (!file_exists($path)) { $this->setMessage($constraint->notFoundMessage, array('{{ file }}' => $path)); return false; } if (!is_readable($path)) { $this->setMessage($constraint->notReadableMessage, array('{{ file }}' => $path)); return false; } if ($constraint->maxSize) { if (ctype_digit((string) $constraint->maxSize)) { $size = filesize($path); $limit = $constraint->maxSize; $suffix = ' bytes'; } else { if (preg_match('/^(\\d+)k$/', $constraint->maxSize, $matches)) { $size = round(filesize($path) / 1000, 2); $limit = $matches[1]; $suffix = ' kB'; } else { if (preg_match('/^(\\d+)M$/', $constraint->maxSize, $matches)) { $size = round(filesize($path) / 1000000, 2); $limit = $matches[1]; $suffix = ' MB'; } else { throw new ConstraintDefinitionException(sprintf('"%s" is not a valid maximum size', $constraint->maxSize)); } } } if ($size > $limit) { $this->setMessage($constraint->maxSizeMessage, array('{{ size }}' => $size . $suffix, '{{ limit }}' => $limit . $suffix, '{{ file }}' => $path)); return false; } } if ($constraint->mimeTypes) { if (!$value instanceof FileObject) { $value = new FileObject($value); } if (!in_array($value->getMimeType(), (array) $constraint->mimeTypes)) { $this->setMessage($constraint->mimeTypesMessage, array('{{ type }}' => '"' . $value->getMimeType() . '"', '{{ types }}' => '"' . implode('", "', (array) $constraint->mimeTypes) . '"', '{{ file }}' => $path)); return false; } } return true; }
/** * Resize image * * @param int $width Thumbnail width * @param int $height Thumbnail height * @param string $fileName Source file name * @return \Response Image content */ public function resize($width, $height, $fileName) { $destFile = $this->createThumb($width, $height, $fileName); $fileContent = $this->getFileContent($destFile); $file = new SymfonyFile($destFile); return response()->make($fileContent, 200, ['content-type' => $file->getMimeType()]); }
/** * @param File $file * * @return NotImageGivenException */ public static function create(File $file) { $msg = sprintf('File "%s" is not an image, expected mime type is image/*, given - ', $file->getPathname(), $file->getMimeType()); $me = new static($msg); $me->failedFile = $file; return $me; }
/** * @param array $parameters * * @return mixed|void */ public function missingMethod($parameters = array()) { if (is_array($parameters)) { $parameters = implode('/', $parameters); } # If parameters is a file if ($file = $this->path($parameters)) { $response = \with(new AssetCollection(array(new FileAsset($file))))->dump(); } elseif ($aParameters = json_decode($parameters, TRUE)) { array_walk($aParameters, function (&$item) { $item = new FileAsset($this->path($item)); }); $response = \with(new AssetCollection($aParameters))->dump(); } if (isset($response)) { $headers = array(); if (preg_match('/.css/i', $parameters)) { $headers['Content-Type'] = 'text/css'; } elseif (preg_match('/.js/i', $parameters)) { $headers['Content-Type'] = 'text/javascript'; } elseif (preg_match('/.html|.htm|.php/i', $parameters)) { $headers['Content-Type'] = 'text/html'; } else { $file = new File($file); $mime = $file->getMimeType(); if ($mime) { $headers['Content-Type'] = $mime; } else { $headers['Content-Type'] = 'text/html'; } } return Response::make($response, 200, $headers); } return Response::make('', 404); }
/** * @Route("/download/{resource}", name="bkstg_resource_download_resource") * @ParamConverter("resource", class="BkstgResourceBundle:Resource") */ public function downloadAction(Resource $resource) { $file = new File($resource->getAbsolutePath()); $headers = array('Content-Type' => $file->getMimeType(), 'Content-Disposition' => 'attachment; filename="' . $resource->getPath() . '"'); $filename = $resource->getAbsolutePath(); return new HttpFoundation\Response(file_get_contents($filename), 200, $headers); }
/** * Given a single File, assuming is an image, create a new * Image object containing all needed information. * * This method also persists and flush created entity * * @param File $file File where to get the image * * @return ImageInterface Image created * * @throws InvalidImageException File is not an image */ public function createImage(File $file) { $fileMime = $file->getMimeType(); if ('application/octet-stream' === $fileMime) { $imageSizeData = getimagesize($file->getPathname()); $fileMime = $imageSizeData['mime']; } if (strpos($fileMime, 'image/') !== 0) { throw new InvalidImageException(); } $extension = $file->getExtension(); if (!$extension && $file instanceof UploadedFile) { $extension = $file->getClientOriginalExtension(); } /** * @var ImageInterface $image */ $image = $this->imageFactory->create(); if (!isset($imageSizeData)) { $imageSizeData = getimagesize($file->getPathname()); } $name = $file->getFilename(); $image->setWidth($imageSizeData[0])->setHeight($imageSizeData[1])->setContentType($fileMime)->setSize($file->getSize())->setExtension($extension)->setName($name); return $image; }
public function testGetMimeTypeUsesMimeTypeGuessers() { $file = new File(__DIR__ . '/Fixtures/test.gif'); $guesser = $this->createMockGuesser($file->getPathname(), 'image/gif'); MimeTypeGuesser::getInstance()->register($guesser); $this->assertEquals('image/gif', $file->getMimeType()); }
public function setFileAttribute(\Symfony\Component\HttpFoundation\File\File $file) { $this->attributes['file'] = $file; $this->original_name = $file instanceof UploadedFile ? $file->getClientOriginalName() : $file->getFilename(); $this->size = $file->getSize(); $this->content_type = $file->getMimeType(); }
/** * @param $imageFileObject * @param $finalMimeType * * @dataProvider imagesAsOctetStreamProvider */ public function testCreateImagesFromApplicationOctetStream(File $imageFileObject, $finalMimeType) { $this->assertEquals('application/octet-stream', $imageFileObject->getMimeType()); $image = $this->imageManager->createImage($imageFileObject); $this->assertInstanceOf('Elcodi\\Component\\Media\\Entity\\Interfaces\\ImageInterface', $image); $this->assertEquals($finalMimeType, $image->getContentType()); }
/** * @param Closure $callback * @param InterventionRequest $interventionRequest * @return Response */ public function getResponse(Closure $callback, InterventionRequest $interventionRequest) { try { $this->cacheFile = new File($this->cacheFilePath); $response = new Response(file_get_contents($this->cacheFile->getPathname()), Response::HTTP_OK, ['Content-Type' => $this->cacheFile->getMimeType(), 'Content-Disposition' => 'filename="' . $this->realImage->getFilename() . '"', 'X-Generator-Cached' => true]); $response->setLastModified(new \DateTime(date("Y-m-d H:i:s", $this->cacheFile->getMTime()))); } catch (FileNotFoundException $e) { if (is_callable($callback)) { $image = $callback($interventionRequest); if ($image instanceof Image) { $this->saveImage($image); $this->cacheFile = new File($this->cacheFilePath); if (null !== $this->dispatcher) { // create the ImageSavedEvent and dispatch it $event = new ImageSavedEvent($image, $this->cacheFile); $this->dispatcher->dispatch(ImageSavedEvent::NAME, $event); } // send HTTP header and output image data $response = new Response(file_get_contents($this->cacheFile->getPathname()), Response::HTTP_OK, ['Content-Type' => $image->mime(), 'Content-Disposition' => 'filename="' . $this->realImage->getFilename() . '"', 'X-Generator-First-Render' => true]); $response->setLastModified(new \DateTime('now')); } else { throw new \RuntimeException("Image is not a valid InterventionImage instance.", 1); } } else { throw new \RuntimeException("No image handle closure defined", 1); } } $this->initializeGarbageCollection(); return $response; }
public function thumb(Request $request, $id) { $photo = Photo::findOrFail($id); $file = new File($photo->path); $photo->makeThumbnail(); $headers = array('Content-Type: ' . $file->getMimeType()); return response()->download($photo->path . '.' . $file->guessExtension(), $photo->name, $headers); }
/** * Returns the mime type of the file. * * The mime type is guessed using the functions finfo(), mime_content_type() * and the system binary "file" (in this order), depending on which of those * is available on the current operating system. * * @returns string The guessed mime type, e.g. "application/pdf" */ public function getMimeType() { $mimeType = parent::getMimeType(); if (null === $mimeType) { $mimeType = $this->mimeType; } return $mimeType; }
/** * Constructor. * * @param File $file A File instance */ public function __construct(File $file) { if ($file instanceof UploadedFile) { parent::__construct($file->getPathname(), $file->getClientOriginalName(), $file->getClientMimeType(), $file->getClientSize(), $file->getError(), true); } else { parent::__construct($file->getPathname(), $file->getBasename(), $file->getMimeType(), $file->getSize(), 0, true); } }
/** * Returns the mime type of the file. * * The mime type is guessed using the functions finfo(), mime_content_type() * and the system binary "file" (in this order), depending on which of those * is available on the current operating system. * * @returns string The guessed mime type, e.g. "application/pdf" */ public function getMimeType() { $mimeType = parent::getMimeType(); if (is_null($mimeType)) { $mimeType = $this->mimeType; } return $mimeType; }
/** * Transform image to base 64 * @param string $path relative path to image from bundle directory * @return string base64 encoded image */ public function image64($path) { $file = new File($path, false); if (!$file->isFile() || 0 !== strpos($file->getMimeType(), 'image/')) { return; } $binary = file_get_contents($path); return sprintf('data:image/%s;base64,%s', $file->guessExtension(), base64_encode($binary)); }
/** * Determines MIME type of response body. * * @return null|string */ protected function getResponseMimeType() { $tmpFilename = tempnam(sys_get_temp_dir(), 'collmexphp_'); file_put_contents($tmpFilename, $this->responseBody); $file = new File($tmpFilename); $mimeType = $file->getMimeType(); unlink($tmpFilename); return $mimeType; }
/** * @return mixed * @VirtualProperty */ public function getProductImage() { $filePath = __DIR__ . '/../../../web/productPhoto/' . $this->image; if (file_exists($filePath)) { $file = new File($filePath); return array('fileInfo' => array('type' => $file->getMimeType(), 'encodeType' => 'base64'), 'fileInBinary' => base64_encode(file_get_contents($file->getPathname()))); } return null; }
/** * @param File|null $file */ public function setFile(File $file = null) { $this->file = $file; $this->fileMimeType = $this->file->getMimeType(); $this->fileSize = $this->file->getSize(); if ($this->file instanceof UploadedFile) { $this->fileOriginalName = $this->file->getClientOriginalName(); } // dump($this); }
/** * Use Symfony components to guess the content type. * * @return string * The mime-type */ public function getMimeType() { if (!is_null($this->mime_type)) { return $this->mime_type; } if ($this->info instanceof SymfonyFile) { return $this->mime_type = $this->info->getMimeType(); } return $this->mime_type = 'application/octet-stream'; }
public function generateAssetAction($file) { $loader = $this->app['resources.assets.loader']; $path = $loader->load($file); if ($path === null) { $this->app->abort(404, "Zasób {$file} nie istnieje."); } $assetFile = new File($path); return $this->app->sendFile($path, 200, array('Content-Type' => $assetFile->getMimeType())); }
/** * @param File $file * @return bool */ public function isImage(File $file) { $imageMimes = ['bmp' => 'image/bmp', 'gif' => 'image/gif', 'jpeg' => ['image/jpeg', 'image/pjpeg'], 'jpg' => ['image/jpeg', 'image/pjpeg'], 'jpe' => ['image/jpeg', 'image/pjpeg'], 'png' => 'image/png', 'tiff' => 'image/tiff', 'tif' => 'image/tiff']; $mime = $file->getMimeType(); foreach ($imageMimes as $imageMime) { if (in_array($mime, (array) $imageMime)) { return true; } } return false; }
/** * @param string|null $pathname */ public function __construct($pathname = null) { $this->pathname = $pathname; if ($pathname) { $file = new SfFile($pathname); $this->name = $file->getBasename(); $this->id = $this->name; $this->mimeType = $file->getMimeType(); $this->size = $file->getSize(); } }
/** * Creates a file object from a file on the disk. */ public function fromFile($filePath) { if ($filePath === null) { return; } $file = new FileObj($filePath); $this->file_name = $file->getFilename(); $this->file_size = $file->getSize(); $this->content_type = $file->getMimeType(); $this->disk_name = $this->getDiskName(); $this->putFile($uploadedFile->getRealPath(), $this->disk_name); }
/** * Replaces the current file with a new file. * * @param UploadedFile $file The target file * @param File $filesystemFile The source file */ public function replaceFromFilesystem(UploadedFile $file, File $filesystemFile) { $file->setOriginalFilename($filesystemFile->getBasename()); $file->setExtension($filesystemFile->getExtension()); $file->setMimeType($filesystemFile->getMimeType()); $file->setSize($filesystemFile->getSize()); $storage = $this->getStorage($file); if ($filesystemFile->getSize() > $this->container->get("partkeepr_systemservice")->getFreeDiskSpace()) { throw new DiskSpaceExhaustedException(); } $storage->write($file->getFullFilename(), file_get_contents($filesystemFile->getPathname()), true); }
/** * Get Handle to Path * * @param string $path * * @return File */ private function getHandleToPath($path) { $path = $this->rootDir . '/' . $this->stripQueryString($path); if (is_file($path)) { $handle = new File($path); if (preg_match('/image/', $handle->getMimeType())) { $handle = new Image($handle->getPathname()); } return $handle; } return null; }
/** * @return MediaType|null */ public function classify($filename) { $file = new File($filename); $mimetype = $file->getMimeType(); $mediaType = null; if ($mimetype) { $mediaType = $this->mediaTypes->lookup($mimetype); } if (!$mediaType) { $mediaType = $this->mediaTypes->get($this->fallbackMediaType); } return $mediaType; }
/** * Set file. * * @param UploadedFile $file * * @return $this */ public function setFile(UploadedFile $file = null) { $this->file = $file; $this->setUpdatedAt(new \DateTime()); if ($file) { $this->mimeType = $file->getMimeType(); $this->fileSize = $file->getSize(); } else { $this->mimeType = null; $this->fileSize = null; } return $this; }
/** * {@inheritDoc} */ public function create(File $file) { $mc = $this->getMediaClass(); $baseFile = new $mc(); $baseFile->setPath($file->getPathname()); $baseFile->setName($file->getClientOriginalName()); if ($baseFile instanceof BaseFile) { $baseFile->setCreatedAt(new \DateTime()); $baseFile->setSize($file->getSize()); $baseFile->setContentType($file->getMimeType()); } return $baseFile; }
/** * @param \App\Events\Files\Uploaded $event * * @return bool */ public function handle(Uploaded $event) { $uploadUuid = $event->uploadUuid; $file = new SymfonyFile($path = app('filestream')->getAbsolutePath($uploadUuid)); if ($allowedMimeTypes = config('filesystems.allowed_mimetypes')) { if (is_array($allowedMimeTypes) && !is_null($fileMimeType = $file->getMimeType())) { if (!in_array($fileMimeType, $allowedMimeTypes)) { unlink($path); throw new FileStreamExceptions\MimeTypeNotAllowedException(); } } } return true; }