/** * {@inheritdoc} */ public function saveFile(UploadedFile $uploadedFile, $fileName) { $stream = fopen($uploadedFile->getRealPath(), 'r+'); $result = $this->filesystem->writeStream($this->getMediaBasePath() . '/' . $fileName . '.' . $uploadedFile->guessClientExtension(), $stream); fclose($stream); return $result; }
protected function savePhoto(UploadedFile $photo) { $fileName = str_random(40) . '.' . $photo->guessClientExtension(); $destinationPath = public_path() . '/upload/gambar/'; $photo->move($destinationPath, $fileName); return $fileName; }
/** * @param UploadedFile $file * * @return \WellCommerce\Bundle\MediaBundle\Entity\MediaInterface */ protected function createMediaFromUploadedFile(UploadedFile $file) { $media = $this->initResource(); $media->setName($file->getClientOriginalName()); $media->setExtension($file->guessClientExtension()); $media->setMime($file->getClientMimeType()); $media->setSize($file->getClientSize()); return $media; }
/** * Create a file row from the given file * @param UploadedFile $file * @return mixed */ public function createFromFile(UploadedFile $file) { $fileName = FileHelper::slug($file->getClientOriginalName()); $exists = $this->model->whereFilename($fileName)->first(); if ($exists) { throw new \InvalidArgumentException('File slug already exists'); } return $this->model->create(['filename' => $fileName, 'path' => "/assets/media/{$fileName}", 'extension' => $file->guessClientExtension(), 'mimetype' => $file->getClientMimeType(), 'filesize' => $file->getFileInfo()->getSize()]); }
/** * Create a file row from the given file * @param UploadedFile $file * @return mixed */ public function createFromFile(UploadedFile $file) { $fileName = FileHelper::slug($file->getClientOriginalName()); $exists = $this->model->whereFilename($fileName)->first(); if ($exists) { $fileName = $this->getNewUniqueFilename($fileName); } return $this->model->create(['filename' => $fileName, 'path' => config('asgard.media.config.files-path') . "{$fileName}", 'extension' => $file->guessClientExtension(), 'mimetype' => $file->getClientMimeType(), 'filesize' => $file->getFileInfo()->getSize(), 'folder_id' => 0]); }
/** * {@inheritdoc} */ public function save(UploadedFile $file, $dir) { $media = new Media(); $media->setName($file->getClientOriginalName()); $media->setExtension($file->guessClientExtension()); $media->setMime($file->getClientMimeType()); $media->setSize($file->getClientSize()); $this->_em->persist($media); $this->_em->flush(); return $media; }
/** * @param UserModel $user * @param UploadedFile $file * @param ImageTypeModel $image_type * * @throws InvalidCreationException * @return ImageModel */ public function createUpload($owner, $file, $uploadTarget, $uploadInfo) { // Check that image is valid $ext = $file->guessClientExtension(); if ($ext == "jpeg") { $ext = "jpg"; } $size = $file->getClientSize(); if (!in_array($ext, $this->valid_exts)) { throw new InvalidCreationException('File format unacceptable: ' . $ext); } if (!$size || $size > $this->max_size) { throw new InvalidCreationException('File is too large: ' . strval($size)); } if ($uploadInfo['unique'] == true) { try { $target = \DB::table('upload_map')->where('owner_hash', $uploadTarget->hash)->where('upload_type', $uploadInfo['type'])->first(); if ($target) { $previousUpload = $this->uploadRepository->getByUploadWithTypeAndTarget($uploadTarget, $uploadInfo['type'])->first(); $this->deleteUpload($previousUpload); \DB::table('upload_map')->where('upload_hash', $previousUpload->hash)->delete(); } } catch (ModelNotFoundException $e) { //To be expected if there is no previous } } $upload_dir = storage_path() . '/app/' . $owner->hash; // Create the path for the upload file if (!\File::exists($upload_dir)) { \File::makeDirectory($upload_dir, 0775); } // Create data for object $data = []; $data['user_id'] = $owner->id; $data['extension'] = $ext; $data['upload_type'] = $uploadInfo['type']; $data['path'] = $upload_dir; // Create the object // Create the full image if ($ext != 'pdf') { \Cloudder::upload($file); $publicID = \Cloudder::getPublicId(); } else { \Cloudder::upload($file); $publicID = \Cloudder::getPublicId(); } $data['hash'] = $publicID; $upload = $this->uploadRepository->create($data); \DB::table('upload_map')->insert(['upload_hash' => $publicID, 'owner_hash' => $uploadTarget->hash, 'upload_type' => $uploadInfo['type'], 'created_at' => date('Y-m-d G:i:s'), 'updated_at' => date('Y-m-d G:i:s')]); \Log::info('New upload created', $upload->toArray()); return $upload; }
/** * Upload file * * @ORM\PrePersist() * @ORM\PreUpdate() */ public function preUpload() { if (null === $this->imageFile) { return; } $ext = $this->imageFile->guessClientExtension(); if (!in_array($ext, array('png', 'jpg', 'jpeg'))) { return; } $this->temp = $this->image; $this->tempName = sha1(uniqid(mt_rand(), true)) . '.' . $ext; $this->image = self::IMAGE_PATH . '/' . $this->tempName; }
public function upload(UploadedFile $file, $dir) : MediaInterface { if (!$file->isValid()) { throw new InvalidMediaException('Passed file object is not valid'); } /** @var MediaInterface $media */ $media = $this->manager->initResource(); $media->setName($file->getClientOriginalName()); $media->setExtension($file->guessClientExtension()); $media->setMime($file->getClientMimeType()); $media->setSize($file->getClientSize()); $errors = $this->validatorHelper->validate($media); if (0 !== count($errors)) { throw new InvalidMediaException($errors); } $this->manager->createResource($media); $file->move($this->getUploadDir($dir), $media->getPath()); return $media; }
/** * {@inheritDoc} */ public function load(ObjectManager $manager) { $rootPath = $this->container->get('kernel')->getRootDir() . '/../web/themes/wellcommerce/assets/prod/'; $uploader = $this->container->get('media.manager.admin'); $uploadPath = $uploader->getUploadRootDir('images'); $filesystem = $this->container->get('filesystem'); foreach (self::$samples as $photo) { $image = new UploadedFile($rootPath . $photo, $photo, 'image/jpeg', filesize($rootPath . $photo)); $media = new Media(); $media->setName($image->getClientOriginalName()); $media->setExtension($image->guessClientExtension()); $media->setMime($image->getClientMimeType()); $media->setSize($image->getClientSize()); $manager->persist($media); $filesystem->copy($rootPath . $photo, $uploadPath . '/' . $media->getPath()); $this->setReference('photo_' . $photo, $media); } $manager->flush(); }
/** * Create a unique filename based on the original filename. * * This checks the filesystem for other files that start with the original base name. * It does not check the database to avoid overwriting files that are not persisted * to the database for whatever reason. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * * @return string */ public function createUniqueFileName($file) { $ext = '.' . $file->guessExtension(); if ($ext === '.txt' && null !== ($clientExt = $file->guessClientExtension())) { $ext = '.' . $clientExt; } $basename = trim(str_replace('.' . $file->getClientOriginalExtension(), '', $file->getClientOriginalName())); $basename = str_replace(' ', '-', $basename); $basename = strtolower($basename); $existing = $this->filesystem->listKeys($basename); if (isset($existing['keys'])) { $existing = $existing['keys']; } if (count($existing)) { $ids = [1]; foreach ($existing as $neighbor) { $neighbor = str_replace($ext, '', $neighbor); if (preg_match('/(\\d+)$/', $neighbor, $matches)) { $ids[] = intval($matches[1]); } } rsort($ids); $id = reset($ids); ++$id; $basename = $basename . '-' . $id; } return $basename . $ext; }
/** * @param UploadedFile $uploadedFile * @return array */ public function handleUpload(UploadedFile $uploadedFile) { $data = array(); if (null !== $uploadedFile && $uploadedFile->isValid()) { $uploadedTempFile = $uploadedFile->getPathname(); $data['originalName'] = $uploadedFile->getClientOriginalName(); $data['filename'] = $this->sanitizeFilename($uploadedFile->getClientOriginalName()); $data['mimeType'] = $uploadedFile->getClientMimeType(); $data['size'] = $uploadedFile->getClientSize(); $data['extension'] = $uploadedFile->getClientOriginalExtension(); if (empty($data['extension'])) { $data['extension'] = $uploadedFile->guessClientExtension(); } $data['width'] = 0; $data['height'] = 0; if ($this->checkIfImage($uploadedFile->getClientOriginalExtension(), $uploadedFile->getClientMimeType())) { $imageInfo = getimagesize($uploadedTempFile); if (!empty($imageInfo)) { $data['width'] = $imageInfo[0]; $data['height'] = $imageInfo[1]; } } $data['binary'] = null; if (file_exists($uploadedTempFile)) { $mediaStream = fopen($uploadedTempFile, 'rb'); $data['binary'] = stream_get_contents($mediaStream); fclose($mediaStream); } } return $data; }
public function testGuessClientExtensionWithIncorrectMimeType() { $file = new UploadedFile(__DIR__ . '/Fixtures/test.gif', 'original.gif', 'image/jpeg', filesize(__DIR__ . '/Fixtures/test.gif'), null); $this->assertEquals('jpeg', $file->guessClientExtension()); }
/** * Move uploaded photo to public/img folder * @param UploadedFile $photo * @return string */ protected function savePhoto(UploadedFile $photo) { $fileName = str_random(40) . '.' . $photo->guessClientExtension(); $destinationPath = public_path() . DIRECTORY_SEPARATOR . 'img'; $photo->move($destinationPath, $fileName); return $fileName; }
/** * @param \Closure|null $func * @param $field * @param UploadedFile $file * @return string */ protected function getFilenameFromFile($func, $field, UploadedFile $file) { if (is_null($func)) { $func = function ($directory, $originalName, $extension) { return RandomFilenamer::get($directory, $extension); }; } return $func($this->{$field}->getDirectoryFullPath(), $file->getClientOriginalName(), $file->guessClientExtension()); }
/** * Get the new filename of file. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @param array $config * * @return string */ protected function getFilename(UploadedFile $file, array $config) { $ext = '.' . ($file->getClientOriginalExtension() ?: $file->guessClientExtension()); return str_finish($this->formatPath($config['path_format']), '/') . md5($file->getFilename()) . $ext; }
/** * Функция для загрузки файлов в систему * @param UploadedFile $file объект UploadedFile, получаемый из объекта Request * @param type $obj объект к которому привязывается загружаемый файл, должен иметь методы addAttachment и getUploadRootDir * @param type $folderPrefix префикс создаваемой папки * @return boolean в случае успеха возвращает true, иначе false. * @throws \Exception В случае отсутствия требуемых методов Exception */ public function upload(UploadedFile $file, $obj, $folderPrefix = 'PA_') { if (!is_object($obj)) { throw new \Exception('Upload file exception: second argument most be object'); } if (!method_exists($obj, 'addAttachment')) { throw new \Exception('Upload file exception: object must have addAttachment() method'); } try { $em = $this->getDoctrine()->getManager(); $attachment = new Core\Attachment(); //create folder if not exist $folder = $this->getUploadRootDir() . '/' . $folderPrefix . $obj->getId(); if (!file_exists($folder) && !is_dir($folder)) { mkdir(trim($folder, '/'), 0777, true); } $filename = $file->getClientOriginalName(); $attachment->setFilename($filename); $attachment->setFilesize($file->getSize()); $attachment->setMimeType($file->guessClientExtension()); $attachment->setFullpath($folder); $attachment->updatedTimestamps(); $obj->addAttachment($attachment); $em->persist($attachment); $em->flush(); $em->clear(); $file->move($folder, $filename); return true; } catch (\Exception $ex) { $logger = $this->get('logger'); $logger->error($ex->getMessage()); return false; } }