/** * Get original name of file. * * @return string */ public function getName() { if ($this->file instanceof UploadedFile) { return $this->file->getClientOriginalName(); } return $this->file->getFilename(); }
public function preUpload() { if (null !== $this->file) { // do whatever you want to generate a unique name $this->file_name = $this->file->getClientOriginalName(); $this->charte_file = uniqid() . '.' . $this->file->guessExtension(); } }
/** * @throws FileException */ public function upload() { if ($this->file instanceof File) { $name = sha1($this->file->getClientOriginalName() . uniqid() . getrandmax()) . '.' . $this->file->guessExtension(); $this->file->move($this->getWeb() . $this->folder, $name); $this->file = $name; } else { throw new FileException('It must be a Symfony\\Component\\HttpFoundation\\File\\File instance'); } }
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(); }
/** * 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); } }
/** * Save uploaded file without validation * * @param File $file * @param string $newLocation * @param string $newName * @throws FileException * @return File */ protected function saveFile(File $file, $newLocation, $newName = "") { $name = $file->getClientOriginalName(); if ($newName) { $name = $newName; } return $file->move($this->createFolderIfNotExist($newLocation), $this->getUniqueFileName($name, $newLocation)); }
public function storeFileInPath($path, File $file, $name = null) { $filename = $name ? $name : $file->getClientOriginalName(); for ($i = 2; file_exists($path . $filename); $i++) { $filename = $i . '_' . $filename; } $file->move($path, $filename); return $filename; }
/** * @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); }
/** * {@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; }
protected function validateFileExtension(File $file, $extensions) { if ($file instanceof UploadedFile) { $filename = $file->getClientOriginalName(); } else { $filename = $file->getFilename(); } $errors = array(); $regex = '/\\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i'; if (!preg_match($regex, $filename)) { $errors[] = "只允许上传以下扩展名的文件:" . $extensions; } return $errors; }
/** * @param File $file * @return string */ protected function getNormalizedFilename(File $file) { if ($file instanceof UploadedFile) { $originalFilename = $file->getClientOriginalName(); $size = $file->getClientSize(); } else { $originalFilename = $file->getFilename(); $size = $file->getSize(); } $name = preg_replace(self::REGEX_FILENAME_EXT, '', $originalFilename); $name = preg_replace(self::REGEX_INVALID_FILENAME_CHARS, '_', $name); $hash = substr(sha1(json_encode(array(time(), $name, $size))), 0, 7); $ext = $file->getExtension(); if (!$ext) { $ext = explode('.', $originalFilename); $ext = end($ext); } $filename = sprintf('%s_%s.%s', $name, $hash, $ext); return $filename; }
/** * Enregistre l'icône sur le disque. * * @return void */ protected function uploadImage() { $this->deleteImage(); $this->miniature = null; $fichier = new Fichier($this->imageFile->getRealPath()); $this->image = $this->imageFile->getClientOriginalName(); $this->dossier = $this->guessSousDossier(); $fichier->move($this->getImageUploadDir() . DIRECTORY_SEPARATOR . $this->image, false); $image = new Image($fichier->getChemin()); $image->setNomMinifie($this->getTitle(), '-', true, 128); $this->image = $image->getNom(); if ($image->getLargeur() >= $image->getHauteur() && $image->getLargeur() > $this->getLargeurMaximale()) { $image->redimensionne($this->getLargeurMaximale(), null, true); } elseif ($image->getLargeur() < $image->getHauteur() && $image->getHauteur() > $this->getHauteurMaximale()) { $image->redimensionne(null, $this->getHauteurMaximale(), true); } $this->largeur = $image->getLargeur(); $this->hauteur = $image->getHauteur(); $this->setImageFile(null); }
/** * Get the full target name for the uploaded file. * * @return string */ protected function getTargetFileName() { if ($this->final) { return $this->fileName; } // Create a unique filename with a simple pattern $originalName = $this->file->getClientOriginalName(); $extension = $this->file->guessExtension() ?: pathinfo($originalName, PATHINFO_EXTENSION); $pattern = $this->getTargetFileNamePattern(); $fileName = sprintf($pattern, pathinfo($originalName, PATHINFO_FILENAME), $extension); $this->fullPath = $this->getTargetFileDirectory() . DIRECTORY_SEPARATOR . $fileName; $i = 1; while (file_exists($this->fullPath)) { $fileName = sprintf($pattern, pathinfo($originalName, PATHINFO_FILENAME) . "({$i})", $extension); $this->fullPath = $this->getTargetFileDirectory() . DIRECTORY_SEPARATOR . $fileName; $i++; } $this->app['logger.system']->debug("[BoltForms] Setting uploaded file '{$originalName}' to use the name '{$fileName}'.", array('event' => 'extensions')); $this->final = true; return $this->fileName = $fileName; }
public function preUpload() { if (null !== $this->getFile()) { // set the asset title as original file name if title is missing if (null === $this->getTitle()) { $this->setTitle($this->file->getClientOriginalName()); } $filename = sha1(uniqid(mt_rand(), true)); $extension = $this->getFile()->guessExtension(); if (empty($extension)) { //get it from the original name $extension = pathinfo($this->originalFileName, PATHINFO_EXTENSION); } $this->path = $filename . '.' . $extension; } elseif ($this->getStorageLocation() == 'remote' && $this->getRemotePath() !== null) { $fileName = basename($this->getRemotePath()); $this->setOriginalFileName($fileName); // set the asset title as original file name if title is missing if (null === $this->getTitle()) { $this->setTitle($fileName); } } }
/** * Sets file. * * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $file */ public function setFile(File $file = null) { $this->file = $file; if ($file) { // It is required that at least one field changes if you are using doctrine // otherwise the event listeners won't be called and the file is lost $this->updatedAt = new \DateTime('now'); $this->fileType = strtoupper($file->getExtension()); $this->size = $file->getSize(); if ($file instanceof \Symfony\Component\HttpFoundation\File\UploadedFile) { $this->originalName = $file->getClientOriginalName(); if ($this->isNoname) { $this->name = $this->originalName; } } } }
/** * Creates a custom ResourceIcon entity from a File (wich should contain an image). * (for instance if the thumbnail of a resource is changed). * * @param File $file * @param Workspace $workspace (for the storage directory...) * * @return \Claroline\CoreBundle\Entity\Resource\ResourceIcon */ public function createCustomIcon(File $file, Workspace $workspace = null) { $fileName = $file instanceof UploadedFile ? $file->getClientOriginalName() : $file->getFilename(); $this->om->startFlushSuite(); $extension = pathinfo($fileName, PATHINFO_EXTENSION); if (is_null($workspace)) { $dest = $this->thumbDir; $hashName = $this->ut->generateGuid() . '.' . $extension; } else { $dest = $this->thumbDir . DIRECTORY_SEPARATOR . $workspace->getCode(); $hashName = $workspace->getCode() . DIRECTORY_SEPARATOR . $this->ut->generateGuid() . '.' . $extension; } $file->move($dest, $hashName); //entity creation $icon = $this->om->factory('Claroline\\CoreBundle\\Entity\\Resource\\ResourceIcon'); $icon->setRelativeUrl("{$this->basepath}/{$hashName}"); $icon->setMimeType('custom'); $icon->setShortcut(false); $this->om->persist($icon); $this->createShortcutIcon($icon, $workspace); $this->om->endFlushSuite(); return $icon; }
/** * @param File $data * * @return Media */ public function createNew($data) { if ($data instanceof File) { /* @var $data File */ $media = new Media(); if (method_exists($media, 'getClientOriginalName')) { $media->setName($data->getClientOriginalName()); } else { $media->setName($data->getFilename()); } $media->setContent($data); return $media; } }
protected function getOriginalName(File $file) { return $file instanceof UploadedFile ? $file->getClientOriginalName() : $file->getFilename(); }
/** * @param Temp|UploadedFile|File $file * @param array $options * @return array * @throws \Exception */ public function manipulateImage($file, array $options) { // Detect file type if ($file instanceof Temp) { $sanitizedFilename = $this->sanitizeFilename($file->filename); } elseif ($file instanceof UploadedFile) { $sanitizedFilename = $this->sanitizeFilename($file->getClientOriginalName()); } elseif ($file instanceof File) { $actualFilename = str_replace('_source.', '.', $file->getFilename()); $sanitizedFilename = $this->sanitizeFilename($actualFilename); $sourceFile = clone $file; } else { throw new \Exception('Unexpected file of class ' . get_class($file)); } $images = []; $pathParts = pathinfo($sanitizedFilename); // Move uploaded file and rename it as source file if this is needed. // We need to generate unique name if the name is already in use. if (!isset($sourceFile)) { $filename = $pathParts['filename'] . '_source.' . $pathParts['extension']; $sourceFile = $file->move($this->getThumbnailPath(), $filename); } $images['original']['source'] = $sourceFile; // If we have retina factor if ($this->getRetinaFactor()) { // Generate retina image by just copying the source. $retinaFilename = $this->generateRetinaName($sanitizedFilename); FileFacade::copy($sourceFile->getRealPath(), $this->getThumbnailPath() . $retinaFilename); $images['original']['retina'] = Image::make($this->getThumbnailPath() . $retinaFilename); // The original image is scaled down version of the source. $originalImage = Image::make($sourceFile->getRealPath()); $width = round($originalImage->getWidth() / $this->getRetinaFactor()); $height = round($originalImage->getHeight() / $this->getRetinaFactor()); $originalImage->resize($width, $height); $images['original']['original_file'] = $originalImage->save($this->getThumbnailPath() . $sanitizedFilename); // Generate thumbs foreach ($options['thumbnails'] as $thumbnailName => $thumbnailOptions) { // Create retina thumb $images['thumbnails'][$thumbnailName]['retina'] = $this->createThumbnail($sourceFile->getRealPath(), $thumbnailName, $this->generateRetinaName($sanitizedFilename), $thumbnailOptions['width'] * $this->getRetinaFactor(), $thumbnailOptions['height'] * $this->getRetinaFactor(), $thumbnailOptions['type'], array_get($thumbnailOptions, 'color')); // Create original thumb $images['thumbnails'][$thumbnailName]['original'] = $this->createThumbnail($sourceFile->getRealPath(), $thumbnailName, $sanitizedFilename, $thumbnailOptions['width'], $thumbnailOptions['height'], $thumbnailOptions['type'], array_get($thumbnailOptions, 'color')); } } else { // Copy source file. $filename = $this->sanitizeFilename($file->getFilename()); FileFacade::copy($sourceFile->getRealPath(), $this->getThumbnailPath() . $filename); $images['original']['original_file'] = Image::make($this->getThumbnailPath() . $filename); // Generate thumbs foreach ($options['thumbnails'] as $thumbnailName => $thumbnailOptions) { // Create original thumb $images['thumbnails'][$thumbnailName]['original'] = $this->createThumbnail($sourceFile->getRealPath(), $thumbnailName, $sanitizedFilename, $thumbnailOptions['width'], $thumbnailOptions['height'], $thumbnailOptions['type']); } } return $images; }
/** * @param FileInfo $info * * @return array */ protected function extractDataFromFileInfo(FileInfo $info) { $data = []; if ($info instanceof UploadedFile) { $data['original_name'] = $info->getClientOriginalName(); $data['original_extension'] = $info->getClientOriginalExtension(); } return $data; }
public function setSplashscreenA960x720(File $splashscreen) { if (StringUtil::endsWith($splashscreen->getClientOriginalName(), '.9.png')) { $splashscreen->move($this->getUploadRootDir("android"), "splashscreenA960x720.9.png"); } else { $splashscreen->move($this->getUploadRootDir("android"), "splashscreenA960x720.png"); } }
/** * Set file * * @param File $file * @return $this */ public function setFile(File $file = null) { $this->file = $file; if (is_file($this->getAbsolutePath())) { $this->temp = $this->getAbsolutePath(); } if (null !== $file) { $extension = $file->getExtension() ? $file->getExtension() : $file->guessExtension(); if ($file instanceof UploadedFile) { $this->setOriginalName($file->getClientOriginalName()); if (!$extension) { $extension = pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION); } $filename = sha1($file->getClientOriginalName() . rand(0, 99999)) . '.' . $extension; $mimeType = $file->getMimeType(); } else { $this->setOriginalName($file->getFilename()); $filename = sha1($file->getFilename() . rand(0, 99999)) . '.' . $extension; $mimeType = $file->getMimeType(); } $this->setFilename($filename); $this->setMimeType($mimeType); } return $this; }
/** * Upload a file, storing it in the temporary * * @param File $file * @param Media $media * * @throws Exception\MediaFileDeniedException * @return Media */ public function upload(File $file, Media $media = null) { if (!$media instanceof Media) { $media = new $this->class(); } if ($file instanceof UploadedFile) { $extension = $file->getClientOriginalExtension(); $oldName = $file->getClientOriginalName(); } else { $extension = $file->getExtension(); $oldName = $file->getFilename(); } $fileMime = $file->getMimeType(); if (array_key_exists($fileMime, $this->accept) && in_array(strtolower($extension), $this->accept[$fileMime])) { $newFileName = null; // if the media name is set, use it over a hashed one if ($media->getName()) { if ($media->getPath() != $file->getPathname()) { $newFileName = $media->getName(); } } else { $newFileName = md5(time() . rand()) . "." . $extension; } if ($newFileName) { $file = $file->move($this->storePath, $newFileName); } } else { throw new MediaFileDeniedException($fileMime); } if ($file instanceof File) { /** @var Media $media */ if (!$media->getTitle()) { $media->setTitle($oldName); } $oldPath = pathinfo($oldName); if (!$media->getNameOriginal()) { $media->setNameOriginal($oldName); } if (!$media->getName()) { $media->setName($file->getFilename()); } if (!$media->getAlt()) { $media->setAlt($oldPath['filename']); } if (!$media->getCredits()) { $media->setCredits($this->user->getUsername()); } $media->setSrc($this->storeDirectory . $file->getFilename()); $media->setPath($this->storePath . $file->getFilename()); $this->optimiser->optimise($media); $media->setHash(sha1_file($file->getPathname())); } return $media; }
/** * $current_uri String actual uri of the file * $dest_folder String future uri of the file starting from web/upload folder * $lifetime DateTime lifetime of the file. If time goes over this limit, the file will be deleted. **/ public function upload(File $file, $dest_folder = '', \DateTime $lifetime = null) { if ($file instanceof UploadedFile) { if ($file->getError() !== null && $file->getError() !== 0) { throw new UploadException($file->getErrorMessage()); } } //preparing dir name $dest_folder = date('Ymd') . '/' . date('G') . '/' . $dest_folder; //checking mimetypes $mimeTypePassed = false; foreach ($this->allowedMimetypes as $mimeType) { if (preg_match('@' . $mimeType . '@', $file->getMimeType())) { $mimeTypePassed = true; } } if (!$mimeTypePassed) { throw new InvalidMimeTypeException('Only following filetypes are allowed : ' . implode(', ', $this->allowedMimetypes)); } $fs = new Filesystem(); if (!$fs->exists($this->uploadDir . $dest_folder)) { $fs->mkdir($this->uploadDir . $dest_folder); } $em = $this->entityManager; $media = new Media(); $media->setMime($file->getMimeType()); // If there's one, we try to generate a new name $extension = $file->getExtension(); // Sanitizing the filename $slugify = new Slugify(); if ($file instanceof UploadedFile) { if (empty($extension)) { $extension = $file->getClientOriginalExtension(); if (empty($extension)) { $extension = $file->guessClientExtension(); } } $filename = $slugify->slugify(basename($file->getClientOriginalName(), $extension)) . '.' . $extension; } else { if (empty($extension)) { $extension = $file->guessClientExtension(); } $filename = $slugify->slugify(basename($file->getFilename(), $extension)) . '.' . $extension; } // A media can have a lifetime and will be deleted with the cleanup function if (!empty($lifetime)) { $media->setLifetime($lifetime); } // Checking for a media with the same name $mediaExists = $this->entityManager->getRepository('AlpixelMediaBundle:Media')->findOneByUri($dest_folder . $filename); $mediaExists = count($mediaExists) > 0; if ($mediaExists === false) { $mediaExists = $fs->exists($this->uploadDir . $dest_folder . $filename); } if ($mediaExists === true) { $filename = basename($filename, '.' . $extension); $i = 1; do { $media->setName($filename . '-' . $i++ . '.' . $extension); $media->setUri($dest_folder . $media->getName()); $mediaExists = $this->entityManager->getRepository('AlpixelMediaBundle:Media')->findOneByUri($media->getUri()); $mediaExists = count($mediaExists) > 0; if ($mediaExists === false) { $mediaExists = $fs->exists($this->uploadDir . $dest_folder . $filename); } } while ($mediaExists === true); } else { $media->setName($filename); $media->setUri($dest_folder . $media->getName()); } $file->move($this->uploadDir . $dest_folder, $media->getName()); chmod($this->uploadDir . $dest_folder . $media->getName(), 0664); // Getting the salt defined in parameters.yml $secret = $this->container->getParameter('secret'); $media->setSecretKey(hash('sha256', $secret . $media->getName() . $media->getUri())); $em->persist($media); $em->flush(); return $media; }
/** * Get the name of the file * * @param UploadedFile|File|string $file * @return string */ protected function getFileName($file) { if ($file instanceof UploadedFile) { return $file->getClientOriginalName(); } elseif ($file instanceof File) { return $file->getFilename(); } else { return basename($file); } }