/** * 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); }
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); } }
/** * @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); }
/** * @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); }
/** * 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; }
public function testSizeFailing() { $dir = __DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'directory'; $path = $dir . DIRECTORY_SEPARATOR . 'test.copy.gif'; @unlink($path); copy(__DIR__ . '/Fixtures/test.gif', $path); $file = new File($path); @unlink($path); try { $file->getSize(); $this->fail('File::getSize should throw an exception.'); } catch (FileException $e) { } }
private function prepareResponse(File $file, $filename = null) { $mimeType = $file->getMimeType(); if ($mimeType == 'application/pdf') { $disposition = 'inline'; } else { $disposition = 'attachment'; } $response = new Response(); $response->headers->set('Cache-Control', 'private'); $response->headers->set('Content-Type', $mimeType); $response->headers->set('Content-Disposition', $disposition . '; filename="' . ($filename ? $filename : $file->getFilename()) . '"'); $response->headers->set('Content-Length', $file->getSize()); $response->sendHeaders(); readfile($file); return $response; }
public function VisualAction($document) { // Generate response $response = new Response(); // Set headers $filepath = $this->get('kernel')->getRootDir() . "/uploads/formations_documents/" . $document; $oFile = new File($filepath); $response->headers->set('Cache-Control', 'private'); $response->headers->set('Content-type', $oFile->getMimeType()); $response->headers->set('Content-Disposition', 'inline; filepath="' . $oFile->getBasename() . '";'); $response->headers->set('Content-length', $oFile->getSize()); // filename // Send headers before outputting anything $response->sendHeaders(); $response->setContent(file_get_contents($filepath)); return $response; }
/** * @Route("/files/{fileName}") * @Method("GET") */ public function GetFile($fileName) { $finder = new Finder(); $finder->files()->name($fileName)->in('../data'); if ($finder->count() == 0) { return new Response("File " . $fileName . " not found", 404); } $iterator = $finder->getIterator(); $iterator->rewind(); $file = $iterator->current(); $oFile = new File(realpath($file)); $response = new Response(null); $response->headers->set('Cache-Control', 'private'); $response->headers->set('Content-type', $oFile->getMimeType()); $response->headers->set('Content-Disposition', 'attachment; filename="' . $oFile->getBasename() . '";'); $response->headers->set('Content-length', $oFile->getSize()); $response->setContent(file_get_contents($oFile)); return $response; }
/** * Add parameters Kinvey needs to properly process the file. * * @param Guzzle\Common\Event * @return void */ public function beforePrepare(Event $event) { $command = $event['command']; $operation = $command->getOperation(); $client = $command->getClient(); if ($command->getName() !== 'createEntity') { return; } if ($command['collection'] !== 'files' && $client->getCollectionName() !== 'files') { return; } $file = new File($command['path']); $operation->setResponseClass('GovTribe\\LaravelKinvey\\Client\\KinveyFileResponse'); $operation->addParam(new Parameter(array('name' => 'path', 'type' => 'string', 'default' => $command['path']))); $operation->addParam(new Parameter(array('name' => '_public', 'location' => 'json', 'type' => 'boolean', 'default' => isset($command['_public']) ? $command['_public'] : false))); $operation->addParam(new Parameter(array('name' => '_filename', 'location' => 'json', 'type' => 'string', 'default' => !isset($command['_filename']) ? $file->getBaseName() : $command['_filename']))); $operation->addParam(new Parameter(array('name' => 'size', 'location' => 'json', 'type' => 'integer', 'default' => $file->getSize()))); $operation->addParam(new Parameter(array('name' => 'mimeType', 'location' => 'json', 'type' => 'string', 'default' => $file->getMimeType()))); }
/** * * @param $photo_file * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response */ public function getPhotoAction($photo_id) { if (!$this->getUser()) { return $this->redirectToRoute('fos_user_security_login'); } $photo_file = $this->get('doctrine')->getRepository('IuchBundle:Photo')->findOneById($photo_id)->getNom(); // Generate response $response = new Response(); $filepath = $this->get('kernel')->getRootDir() . "/uploads/photos/" . $photo_file; $photoFile = new File($filepath); $response->headers->set('Cache-Control', 'private'); $response->headers->set('Content-type', $photoFile->getMimeType()); $response->headers->set('Content-Disposition', 'inline; filepath="' . $photoFile->getBasename() . '";'); $response->headers->set('Content-length', $photoFile->getSize()); // Send headers before outputting anything $response->sendHeaders(); $response->setContent(file_get_contents($filepath)); return $response; }
protected function createLayout($lang) { $layout = new Layout($lang, "default-{$lang}"); $logoPath = $this->getContainer()->get('kernel')->getRootDir() . '/../web/bundles/donatefront/images/logo.png'; $bgPath = $this->getContainer()->get('kernel')->getRootDir() . '/../web/bundles/donatefront/images/fd-body.jpg'; $f = new File($logoPath); $logo = new UploadedFile($logoPath, 'ulogo.png', $f->getMimeType(), $f->getSize()); $f = new File($bgPath); $bg = new UploadedFile($bgPath, 'ubg.png', $f->getMimeType(), $f->getSize()); $layout->setLogo($logo); $layout->setBackground($bg); $em = $this->getContainer()->get('doctrine.orm.entity_manager'); $repo = $em->getRepository('DonateCoreBundle:Layout'); $defaultLayout = $repo->findDefaultLayout($lang); if (count($defaultLayout) == 0) { $layout->setIsDefault(true); } return $layout; }
public function PictureOrganismeAction($picture) { if (!$this->getUser()) { return $this->redirectToRoute('fos_user_security_login'); } // Generate response $response = new Response(); // Set headers $filepath = $this->get('kernel')->getRootDir() . "/uploads/organismes_pictures/" . $picture; $oFile = new File($filepath); $response->headers->set('Cache-Control', 'private'); $response->headers->set('Content-type', $oFile->getMimeType()); $response->headers->set('Content-Disposition', 'inline; filepath="' . $oFile->getBasename() . '";'); $response->headers->set('Content-length', $oFile->getSize()); // filename // Send headers before outputting anything $response->sendHeaders(); $response->setContent(file_get_contents($filepath)); return $response; }
/** * Validates the file as being supported by Colibri, verifying its size, extension... * @param $file * @return boolean * @throws \Exception */ public function supported(File $file) { $filePath = $file->getPath() . DIRECTORY_SEPARATOR . $file->getFilename(); $fileData = getimagesize($filePath); $maxSize = 1101004; // 1.05 Mo $mimes = array('image/jpeg', 'image/png', 'image/gif'); $fileSize = $file->getSize(); $fileType = $file->getMimeType(); if ($fileSize > $maxSize) { throw new \Exception("File size too big. Got {$fileSize}, max {$maxSize}"); } if (!in_array($fileType, $mimes)) { throw new \Exception("File extension not supported. Got {$fileType}."); } if ($fileData[0] > 2400 || $fileData[1] > 2400) { throw new \Exception("L'image est trop grande, max 2400x2400, reçu {$fileData['0']}x{$fileData['1']}px"); } return true; }
/** * @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; }
public static function downloadAndDelete($fileName, $name = null, array $headers = array()) { $file = new File((string) $fileName); $base = $name ?: basename($fileName); $content = file_get_contents($fileName); $response = Response::make($content); if (!isset($headers['Content-Type'])) { $headers['Content-Type'] = $file->getMimeType(); } if (!isset($headers['Content-Length'])) { $headers['Content-Length'] = $file->getSize(); } if (!isset($headers['Content-disposition'])) { $headers['Content-disposition'] = 'attachment; filename=' . $base; } foreach ($headers as $headerName => $headerValue) { $response->header($headerName, $headerValue); } unlink($fileName); return $response; }
/** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { //add attachment extend field self::addAvatarToUser($schema, $this->attachmentExtension); self::addOwnerToOroFile($schema); //save old avatars to new place $em = $this->container->get('doctrine.orm.entity_manager'); $query = "SELECT id, image, createdAt FROM oro_user WHERE image != ''"; $userImages = $em->getConnection()->executeQuery($query)->fetchAll(\PDO::FETCH_ASSOC); if (!empty($userImages)) { $maxId = (int) $em->getConnection()->executeQuery('SELECT MAX(id) FROM oro_attachment_file;')->fetchColumn(); foreach ($userImages as $userData) { $filePath = $this->getUploadFileName($userData); // file doesn't exists or not readable if (false === $filePath || !is_readable($filePath)) { $this->container->get('logger')->addAlert(sprintf('There\'s no image %s for user %d exists.', $userData['image'], $userData['id'])); continue; } try { $this->container->get('oro_attachment.manager')->copyLocalFileToStorage($filePath, $userData['image']); } catch (\Exception $e) { $this->container->get('logger')->addError(sprintf('File copy error: %s', $e->getMessage())); } $maxId++; $file = new SymfonyFile($filePath); $currentDate = new \DateTime(); $query = sprintf('INSERT INTO oro_attachment_file (id, filename, extension, mime_type, file_size, original_filename, created_at, updated_at, owner_user_id) values (%s, \'%s\', \'%s\', \'%s\', %s, \'%s\', \'%s\', \'%s\', %s);', $maxId, $file->getFileName(), $file->guessExtension(), $file->getMimeType(), $file->getSize(), $userData['image'], $currentDate->format('Y-m-d'), $currentDate->format('Y-m-d'), $userData['id']); $queries->addQuery($query); $query = sprintf('UPDATE oro_user set avatar_id = %d WHERE id = %d;', $maxId, $userData['id']); $queries->addQuery($query); unlink($filePath); } } //delete old avatars field $schema->getTable('oro_user')->dropColumn('image'); }
public function upload(UploadedFile $uploadedFile) { $this->completeFile = null; // pega o range-content (Content-Range: bytes 0-123/400) $range = $this->getContentRange(); $rangeTotal = $range['total']; // pega o nome do arquivo (pode estar no Content-Disposition: attachment; filename="x") $originalName = $this->getContentDispositionFilename($uploadedFile->getClientOriginalName()); if ($uploadedFile->getSize() < (int) $rangeTotal) { // chunk file_put_contents($this->path . $originalName, fopen($uploadedFile->getPathname(), 'r'), FILE_APPEND); $parcialFile = new File($this->path . $originalName); $this->completeFile = $parcialFile->getSize() < (int) $rangeTotal ? null : $parcialFile; return null !== $this->completeFile ? self::COMPLETE : self::PARTIAL; } else { if (is_file($this->path . $originalName)) { $this->completeFile = new File($this->path . $originalName); } else { $this->completeFile = $uploadedFile->move($this->path, $originalName); } return self::COMPLETE; } }
/** * The GET method that displays a file field's file * * @return Image / File */ public function displayFile() { //get the stored path of the original $path = $this->request->input('path'); $data = File::get($path); $file = new SFile($path); $headers = array('Content-Type' => $file->getMimeType(), 'Content-Length' => $file->getSize(), 'Content-Disposition' => 'attachment; filename="' . $file->getFilename() . '"'); return response()->make($data, 200, $headers); }
/** * @param string $type * @return string */ public function getFilesizeNamaFileDisk($type = 'KB') { try { $file = new File($this->getRelativePathNamaFileDisk()); } catch (FileNotFoundException $err) { return '? ' . $type; } if ($file) { return FileSizeFormatter::formatBytes($file->getSize(), $type); } }
/** * 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; }
/** * @param string $type * @return string */ public function getFilesizeFotoDisk($type = 'KB') { $file = new File($this->getRelativePathFotoDisk()); return FileSizeFormatter::formatBytes($file->getSize(), $type); }
/** * @inheritDoc */ public function getSize() { return null === $this->size ? parent::getSize() : $this->size; }
public function fromFile($src, $target_quality = 90) { $imageFileName = strtok(str_replace(appHomeUrl() . '/storage/app/tmp/', '', $src), '?'); if (startWith($imageFileName, self::getPrefix())) { $file = new File(storage_path('app/tmp/' . $imageFileName)); if ($file) { $this->targetFileAsset = asset('storage/app/tmp/' . $imageFileName); $this->imageType = $file->getMimeType(); $this->imageFilePath = $file->getRealPath(); switch (strtolower($this->imageType)) { case 'image/png': $this->imageFileExt = 'png'; $this->image = imagecreatefrompng($this->imageFilePath); break; case 'image/gif': $this->imageFileExt = 'gif'; $this->image = imagecreatefromgif($this->imageFilePath); break; case 'image/jpeg': case 'image/pjpeg': $this->imageFileExt = 'jpg'; $this->image = imagecreatefromjpeg($this->imageFilePath); break; default: $this->saveResult(['success' => false, 'message' => 'Image type was not supported']); return false; } $this->imageFileSize = $file->getSize(); $this->targetQuality = $target_quality; list($imageWidth, $imageHeight) = getimagesize($this->imageFilePath); $this->imageWidth = $imageWidth; $this->imageHeight = $imageHeight; $this->targetFileName = $imageFileName; $this->targetFilePath = $this->imageFilePath; return true; } } $this->saveResult(['success' => false, 'message' => 'Image was not existed']); return false; }
/** * Upload file to FTP * * If file already exists, we do nothing, as it's assumed that files have * unique filenames, and an identical name would mean that the file is * identical to the one already uploaded. * * @param \Symfony\Component\HttpFoundation\File\File $originFile * @param $targetFile * @throws Exception\UploadException * @return string */ public function putByName(File $originFile, $targetFile) { $publicUrl = $this->publicUrl . $targetFile; $tmpDestination = '/' . $this->tmpFolder . $targetFile; $publicDestination = '/' . $this->publicFolder . $targetFile; $this->ftp->preparePaths(array($tmpDestination, $publicDestination)); $alreadyUploaded = $this->ftp->checkIfAlreadyUploaded($originFile->getSize(), $publicDestination, $tmpDestination); if ($alreadyUploaded) { return $publicUrl; } $result = $this->ftp->put($tmpDestination, $originFile->getRealPath()); if ($result) { $this->logger->info('FTP PUT succeeded.'); try { $this->ftp->verifyAndMoveUploadedFile($originFile->getSize(), $tmpDestination, $publicDestination); } catch (FtpException $e) { $this->logger->error($e->getMessage()); throw new UploadException('Error verifying uploaded file.'); } $this->logger->warning('Skipping verification of public url: ' . $publicUrl); } else { $this->logger->error('Error uploading to temp'); throw new UploadException('Error uploading file to storage.'); } return $publicUrl; }
/** * {@inheritdoc} */ public function prepare(Request $request) { $this->headers->set('Content-Length', $this->file->getSize()); if (!$this->headers->has('Accept-Ranges')) { // Only accept ranges on safe HTTP methods $this->headers->set('Accept-Ranges', $request->isMethodSafe() ? 'bytes' : 'none'); } if (!$this->headers->has('Content-Type')) { $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream'); } if ('HTTP/1.0' !== $request->server->get('SERVER_PROTOCOL')) { $this->setProtocolVersion('1.1'); } $this->ensureIEOverSSLCompatibility($request); $this->offset = 0; $this->maxlen = -1; if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) { // Use X-Sendfile, do not send any content. $type = $request->headers->get('X-Sendfile-Type'); $path = $this->file->getRealPath(); // Fall back to scheme://path for stream wrapped locations. if (false === $path) { $path = $this->file->getPathname(); } if (strtolower($type) === 'x-accel-redirect') { // Do X-Accel-Mapping substitutions. // @link http://wiki.nginx.org/X-accel#X-Accel-Redirect foreach (explode(',', $request->headers->get('X-Accel-Mapping', '')) as $mapping) { $mapping = explode('=', $mapping, 2); if (2 === count($mapping)) { $pathPrefix = trim($mapping[0]); $location = trim($mapping[1]); if (substr($path, 0, strlen($pathPrefix)) === $pathPrefix) { $path = $location . substr($path, strlen($pathPrefix)); break; } } } } $this->headers->set($type, $path); $this->maxlen = 0; } elseif ($request->headers->has('Range')) { // Process the range headers. if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) { $range = $request->headers->get('Range'); $fileSize = $this->file->getSize(); list($start, $end) = explode('-', substr($range, 6), 2) + array(0); $end = '' === $end ? $fileSize - 1 : (int) $end; if ('' === $start) { $start = $fileSize - $end; $end = $fileSize - 1; } else { $start = (int) $start; } if ($start <= $end) { if ($start < 0 || $end > $fileSize - 1) { $this->setStatusCode(416); } elseif ($start !== 0 || $end !== $fileSize - 1) { $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1; $this->offset = $start; $this->setStatusCode(206); $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize)); $this->headers->set('Content-Length', $end - $start + 1); } } } } return $this; }
/** * @param File $file */ public function setLocalFile(File $file) { $this->localFile = $file; $this->body = file_get_contents($file->getPathname()); $this->setContentType($file->getMimeType()); $this->setContentLength($file->getSize()); $this->setETag(md5_file($file->getPathname())); }