/** * Create track from local hard drive with job service * * @param MultimediaObject $multimediaObject * @param UploadedFile $file * @param string $profile * @param int $priority * @param string $language * @param array $description * @return MultimediaObject */ public function createTrackFromLocalHardDrive(MultimediaObject $multimediaObject, UploadedFile $trackFile, $profile, $priority, $language, $description) { if (null === $this->profileService->getProfile($profile)) { throw new \Exception("Can't find given profile with name " . $profile); } if (UPLOAD_ERR_OK != $trackFile->getError()) { throw new \Exception($trackFile->getErrorMessage()); } if (!is_file($trackFile->getPathname())) { throw new FileNotFoundException($trackFile->getPathname()); } $pathFile = $trackFile->move($this->tmpPath . "/" . $multimediaObject->getId(), $trackFile->getClientOriginalName()); $this->jobService->addJob($pathFile, $profile, $priority, $multimediaObject, $language, $description); return $multimediaObject; }
/** * @param UploadedFile $file * @param array $methods * * @return mixed|void * * @throws InvalidFileTypeException * @throws InvalidFileException * @throws UploadFileNotSetException * @throws MaxFileSizeExceededException */ public function validate(UploadedFile $file, $methods = [self::VALIDATOR_FILE_SET, self::VALIDATOR_FILE_ERRORS, self::VALIDATOR_BLOCK_FILE_TYPES, self::VALIDATOR_MAX_FILE_SIZE]) { if (in_array(self::VALIDATOR_FILE_ERRORS, $methods) && $file->getError() > 0) { throw new InvalidFileException(sprintf('The file upload had an error("%s: %s")', $file->getError(), $file->getErrorMessage())); } if (in_array(self::VALIDATOR_FILE_SET, $methods) && $file->getFilename() == '') { throw new UploadFileNotSetException(sprintf('No file "%s" was set', $file->getFilename())); } if (in_array(self::VALIDATOR_BLOCK_FILE_TYPES, $methods) && in_array($file->getMimeType(), $this->blockedMimeTypes)) { throw new InvalidFileTypeException(sprintf('The file type "%s" was blocked', $file->getMimeType())); } if (in_array(self::VALIDATOR_MAX_FILE_SIZE, $methods) && $this->maxFileSize !== null && $file->getSize() >= $this->maxFileSize) { throw new MaxFileSizeExceededException(sprintf('File "%s" exceeds the configured maximum filesize of "%s"', $file->getFilename(), $this->maxFilesize)); } }
/** * converts UploadedFile to $_FILES array * * @return array */ public function getFileArray() { $array = array('name' => $this->uploaded_file->getClientOriginalName(), 'type' => $this->uploaded_file->getClientMimeType(), 'tmp_name' => $this->uploaded_file->getPath() . $this->getOSDirectorySeparator() . $this->uploaded_file->getFilename(), 'error' => $this->uploaded_file->getError(), 'size' => $this->uploaded_file->getSize(), 'dimension' => array('width' => 0, 'height' => 0)); if (preg_match('/^image/', $array['type'])) { list($array['dimension']['width'], $array['dimension']['height']) = getimagesize($this->uploaded_file); } return $array; }
public function testErrorIsOkByDefault() { // we can't change this setting without modifying php.ini :( if (ini_get('file_uploads')) { $file = new UploadedFile(__DIR__ . '/Fixtures/test.gif', 'original.gif', 'image/gif', filesize(__DIR__ . '/Fixtures/test.gif'), null); $this->assertEquals(UPLOAD_ERR_OK, $file->getError()); } }
public function testErrorIsOkByDefault() { $file = new UploadedFile( __DIR__.'/Fixtures/test.gif', 'original.gif', 'image/gif', filesize(__DIR__.'/Fixtures/test.gif'), null ); $this->assertEquals(UPLOAD_ERR_OK, $file->getError()); }
/** * Build a \Torann\MediaSort\File\UploadedFile object from * a Symfony\Component\HttpFoundation\File\UploadedFile object. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * * @return \Torann\MediaSort\File\UploadedFile * @throws \Torann\MediaSort\Exceptions\FileException */ protected function createFromObject(SymfonyUploadedFile $file) { $path = $file->getPathname(); $originalName = $file->getClientOriginalName(); $mimeType = $file->getClientMimeType(); $size = $file->getClientSize(); $error = $file->getError(); $uploadFile = new UploadedFile($path, $originalName, $mimeType, $size, $error); if (!$uploadFile->isValid()) { throw new FileException($uploadFile->getErrorMessage($uploadFile->getError())); } return $uploadFile; }
/** * Set a pic from an url into the event */ public function addPicFile(Event $event, UploadedFile $picFile) { if (UPLOAD_ERR_OK != $picFile->getError()) { throw new \Exception($picFile->getErrorMessage()); } if (!is_file($picFile->getPathname())) { throw new FileNotFoundException($picFile->getPathname()); } $path = $picFile->move($this->targetPath . "/" . $event->getId(), $picFile->getClientOriginalName()); $pic = new Pic(); $pic->setUrl(str_replace($this->targetPath, $this->targetUrl, $path)); $pic->setPath($path); $event->setPic($pic); $this->dm->persist($event); $this->dm->flush(); return $event; }
protected function checkFile(UploadedFile $file) { $mime = $file->getClientMimeType(); $info = array('name' => $file->getClientOriginalName(), 'size' => $file->getClientSize(), 'mime' => $mime, 'extension' => $file->getClientOriginalExtension(), 'type' => $mime, 'error' => ''); if ($file->isValid()) { if (!$info['type']) { $info['status'] = 9; $info['error'] = '不支持的文件类型'; } else { $info['status'] = UPLOAD_ERR_OK; } } else { $info['status'] = $file->getError(); $info['error'] = $file->getErrorMessage(); } return $info; }
/** * Add a material from a file into the multimediaObject */ public function addMaterialFile(MultimediaObject $multimediaObject, UploadedFile $materialFile, $formData) { if (UPLOAD_ERR_OK != $materialFile->getError()) { throw new \Exception($materialFile->getErrorMessage()); } if (!is_file($materialFile->getPathname())) { throw new FileNotFoundException($materialFile->getPathname()); } $material = new Material(); $material = $this->saveFormData($material, $formData); $path = $materialFile->move($this->targetPath . "/" . $multimediaObject->getId(), $materialFile->getClientOriginalName()); $material->setPath($path); $material->setUrl(str_replace($this->targetPath, $this->targetUrl, $path)); $multimediaObject->addMaterial($material); $this->dm->persist($multimediaObject); $this->dm->flush(); return $multimediaObject; }
/** * @param UploadedFile $uploadedFile * @return null|string */ protected function handleFileUpload($uploadedFile, $delimiter = ',', $enclosure = '"') { $errMsg = ''; if (!$uploadedFile instanceof UploadedFile) { $errMsg = _("No file selected"); } elseif ($uploadedFile->getSize() == 0 && $uploadedFile->getError() == 0) { $errMsg = _("Larger than upload_max_filesize ") . ini_get(self::KEY_UPLOAD_MAX_FILESIZE); } elseif ($uploadedFile->getClientOriginalExtension() != 'csv') { $errMsg = _('Invalid extension ') . $uploadedFile->getClientOriginalExtension() . ' of file ' . $uploadedFile->getClientOriginalName(); } if (!empty($errMsg)) { return $errMsg; } /** @var LicenseCsvImport */ $licenseCsvImport = $this->getObject('app.license_csv_import'); $licenseCsvImport->setDelimiter($delimiter); $licenseCsvImport->setEnclosure($enclosure); return $licenseCsvImport->handleFile($uploadedFile->getRealPath()); }
/** * File upload callback * Resizes the image according to validation constraints * * @param string $field Field name * @param Symfony\Component\HttpFoundation\File\UploadedFile $file File to process * * @return void */ protected function imageUpload($field, UploadedFile $file) { if (UPLOAD_ERR_OK == $file->getError()) { $asserts = $this->getAsserts()[$field]; foreach ($asserts as $assert) { // Detect image size constraints and resize accordingly if ($assert instanceof Image) { $path = $file->getPathname(); $pathWithExtension = $path . '.' . $file->guessExtension(); rename($path, $pathWithExtension); // ImageWorkshop relies on the file's extension for encoding try { $this->resize($pathWithExtension, $assert->maxWidth, $assert->maxHeight); } catch (ImageWorkshopException $e) { } rename($pathWithExtension, $path); } } } }
/** * Upload a single file * @param UploadedFile $file * @return \HealthCareAbroad\MediaBundle\Entity\Media|unknown */ public function uploadFile(UploadedFile $file) { if (!$file->isValid()) { return $file->getError(); } $caption = $file->getClientOriginalName(); $filename = $this->generateUniqueFilename($file); $file->move($this->uploadDirectory, $filename); $imageAttributes = getimagesize($this->uploadDirectory . '/' . $filename); $media = new Media(); $media->setName($filename); $media->setContentType($imageAttributes['mime']); $media->setCaption($caption); $media->setContext(0); $media->setUuid(time()); $media->setWidth($imageAttributes[0]); $media->setHeight($imageAttributes[1]); $this->entityManager->persist($media); $this->entityManager->flush($media); return $media; }
/** * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file */ public function fromUploadFile($file) { if (!empty($file)) { $errorCode = $file->getError(); if ($errorCode === UPLOAD_ERR_OK) { $file_path = $file->getRealPath(); $type = exif_imagetype($file_path); if ($type) { $extension = image_type_to_extension($type); $srcFilename = uniqid('js_cropper_' . time() . '_') . $extension; $this->srcUrl = asset('storage/app/tmp/' . $srcFilename); $srcPath = storage_path('app/tmp/' . $srcFilename); if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG) { if (file_exists($srcPath)) { unlink($srcPath); } $result = move_uploaded_file($file_path, $srcPath); if ($result) { $this->srcPath = $srcPath; $this->type = $type; $this->extension = $extension; return true; } else { $this->msg = $this->codeToMessage(UPLOAD_ERR_CANT_WRITE); } } else { $this->msg = $this->codeToMessage(UPLOAD_ERR_EXTENSION); } } else { $this->msg = $this->codeToMessage(UPLOAD_ERR_NO_FILE); } } else { $this->msg = $this->codeToMessage($errorCode); } } else { $this->msg = $this->codeToMessage(UPLOAD_ERR_NO_FILE); } return false; }
/** * Set a pic from an url into the series */ public function addPicFile(Series $series, UploadedFile $picFile, $isBanner = false, $bannerTargetUrl = "") { if (UPLOAD_ERR_OK != $picFile->getError()) { throw new \Exception($picFile->getErrorMessage()); } if (!is_file($picFile->getPathname())) { throw new FileNotFoundException($picFile->getPathname()); } $path = $picFile->move($this->targetPath . "/" . $series->getId(), $picFile->getClientOriginalName()); $pic = new Pic(); $pic->setUrl(str_replace($this->targetPath, $this->targetUrl, $path)); $pic->setPath($path); if ($isBanner) { $pic->setHide(true); $pic->addTag('banner'); $series = $this->addBanner($series, $pic->getUrl(), $bannerTargetUrl); } // TODO: add pic the latest if it is banner $series->addPic($pic); $this->dm->persist($series); $this->dm->flush(); return $series; }
public function testUploadErrNoFile() { $file = new UploadedFile('', '', null, 0, UPLOAD_ERR_NO_FILE, true); $this->assertEquals(0, $file->getSize()); $this->assertEquals(UPLOAD_ERR_NO_FILE, $file->getError()); $this->assertFalse($file->getSize(), 'SplFile::getSize() returns false on error'); $this->assertInternalType('integer', $file->getClientSize()); $request = new Request(array(), array(), array(), array(), array('f1' => $file, 'f2' => array('name' => null, 'type' => null, 'tmp_name' => null, 'error' => UPLOAD_ERR_NO_FILE, 'size' => 0)), array('REQUEST_METHOD' => 'POST', 'HTTP_HOST' => 'dunglas.fr', 'HTTP_X_SYMFONY' => '2.8'), 'Content'); $psrRequest = $this->factory->createRequest($request); $uploadedFiles = $psrRequest->getUploadedFiles(); $this->assertEquals(UPLOAD_ERR_NO_FILE, $uploadedFiles['f1']->getError()); $this->assertEquals(UPLOAD_ERR_NO_FILE, $uploadedFiles['f2']->getError()); }
/** * Creates a PSR-7 UploadedFile instance from a Symfony one. * * @param UploadedFile $symfonyUploadedFile * * @return UploadedFileInterface */ private function createUploadedFile(UploadedFile $symfonyUploadedFile) { return new DiactorosUploadedFile($symfonyUploadedFile->getRealPath(), $symfonyUploadedFile->getSize(), $symfonyUploadedFile->getError(), $symfonyUploadedFile->getClientOriginalName(), $symfonyUploadedFile->getClientMimeType()); }
/** * @param UploadedFile $file * @return string * @throws \Vendor\GalleryBundle\Exception\FileUploadException */ public function uploadPictureAndReturnUrl(UploadedFile $file) { $allowedExts = array("gif", "jpeg", "jpg", "png"); $allowedTypes = array("image/gif", "image/jpeg", "image/pjpeg", "image/x-png", "image/png"); $maxFileSize = 200000; $validationErrors = array(); if (!$file->isValid()) { $validationErrors[] = "Return Code: " . $file->getError(); } if (!in_array($file->getClientMimeType(), $allowedTypes)) { $validationErrors[] = 'Invalid file type.'; } $temp = explode(".", $file->getClientOriginalName()); $extension = end($temp); if (!in_array($extension, $allowedExts)) { $validationErrors[] = 'Invalid extension'; } if ($file->getClientSize() > $maxFileSize) { $validationErrors[] = 'File too big (' . $file->getClientSize() . '). Max file size: ' . $maxFileSize; } if (count($validationErrors) > 0) { throw new FileUploadException(implode('\\n', $validationErrors)); } $imgDirPath = $this->getBaseWebPath() . $this->getBundleWebPath(); $filePath = $imgDirPath . $file->getClientOriginalName(); move_uploaded_file($file->getRealPath(), $filePath); return 'images/' . $file->getClientOriginalName(); }
/** * Create a new file instance from a base instance. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @return static */ public static function createFromBase(SymfonyUploadedFile $file) { return $file instanceof static ? $file : new static($file->getPathname(), $file->getClientOriginalName(), $file->getClientMimeType(), $file->getClientSize(), $file->getError()); }
/** * Process file uploaded * * @param UploadedFile $fileBeingUploaded * @param int $parentId Parent id owning files being saved * @param string $parentType Parent Type owning files being saved (product, category, content, etc.) * @param string $objectType Object type, e.g. image or document * @param array $validMimeTypes an array of valid mime types. If empty, any mime type is allowed. * @param array $extBlackList an array of blacklisted extensions. * @return ResponseRest * * @since 2.3 */ public function processFile($fileBeingUploaded, $parentId, $parentType, $objectType, $validMimeTypes = array(), $extBlackList = array()) { $fileManager = $this->getFileManager(); // Validate if file is too big if ($fileBeingUploaded->getError() == 1) { $message = $this->getTranslator()->trans('File is too large, please retry with a file having a size less than %size%.', array('%size%' => ini_get('upload_max_filesize')), 'core'); throw new ProcessFileException($message, 403); } $message = null; $realFileName = $fileBeingUploaded->getClientOriginalName(); if (!empty($validMimeTypes)) { $mimeType = $fileBeingUploaded->getMimeType(); if (!isset($validMimeTypes[$mimeType])) { $message = $this->getTranslator()->trans('Only files having the following mime type are allowed: %types%', ['%types%' => implode(', ', array_keys($validMimeTypes))]); } else { $regex = "#^(.+)\\.(" . implode("|", $validMimeTypes[$mimeType]) . ")\$#i"; if (!preg_match($regex, $realFileName)) { $message = $this->getTranslator()->trans("There's a conflict between your file extension \"%ext\" and the mime type \"%mime\"", ['%mime' => $mimeType, '%ext' => $fileBeingUploaded->getClientOriginalExtension()]); } } } if (!empty($extBlackList)) { $regex = "#^(.+)\\.(" . implode("|", $extBlackList) . ")\$#i"; if (preg_match($regex, $realFileName)) { $message = $this->getTranslator()->trans('Files with the following extension are not allowed: %extension, please do an archive of the file if you want to upload it', ['%extension' => $fileBeingUploaded->getClientOriginalExtension()]); } } if ($message !== null) { throw new ProcessFileException($message, 415); } $fileModel = $fileManager->getModelInstance($objectType, $parentType); $parentModel = $fileModel->getParentFileModel(); if ($parentModel === null || $fileModel === null || $fileBeingUploaded === null) { throw new ProcessFileException('', 404); } $defaultTitle = $parentModel->getTitle(); if (empty($defaultTitle) && $objectType !== 'image') { $defaultTitle = $fileBeingUploaded->getClientOriginalName(); } $fileModel->setParentId($parentId)->setLocale(Lang::getDefaultLanguage()->getLocale())->setTitle($defaultTitle); $fileCreateOrUpdateEvent = new FileCreateOrUpdateEvent($parentId); $fileCreateOrUpdateEvent->setModel($fileModel); $fileCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded); $fileCreateOrUpdateEvent->setParentName($parentModel->getTitle()); // Dispatch Event to the Action $this->dispatch(TheliaEvents::IMAGE_SAVE, $fileCreateOrUpdateEvent); $this->adminLogAppend($this->getAdminResources()->getResource($parentType, static::MODULE_RIGHT), AccessManager::UPDATE, $this->getTranslator()->trans('Saving %obj% for %parentName% parent id %parentId%', array('%parentName%' => $fileCreateOrUpdateEvent->getParentName(), '%parentId%' => $fileCreateOrUpdateEvent->getParentId(), '%obj%' => $objectType))); //return new ResponseRest(array('status' => true, 'message' => '')); return $fileCreateOrUpdateEvent; }
/** * Returns the upload error. * * If the upload was successful, the constant UPLOAD_ERR_OK is returned. * Otherwise one of the other UPLOAD_ERR_XXX constants is returned. * * @return int upload error */ public function getError() { return $this->uploadedFile->getError(); }
/** * Validate the input file. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @param array $config * * @return bool|string */ public function fileHasError(UploadedFile $file, array $config) { $error = false; if (!$file->isValid()) { $error = $file->getError(); } elseif ($file->getSize() > $config['max_size']) { $error = 'upload.ERROR_SIZE_EXCEED'; } elseif (!empty($config['allow_files']) && !in_array('.' . $file->guessExtension(), $config['allow_files'])) { $error = 'ERROR_TYPE_NOT_ALLOWED'; } return $error; }
/** * Returns an informative upload error message. * * Copied from UploadedFile because its only public since 2.4 * * @param UploadedFile $file The file with the error. * * @return string The error message regarding the specified error code */ private function getErrorMessage(UploadedFile $file) { $errorCode = $file->getError(); static $errors = array(UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d kb).', UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.', UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.', UPLOAD_ERR_NO_FILE => 'No file was uploaded.', UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.', UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.', UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.'); $maxFilesize = $errorCode === UPLOAD_ERR_INI_SIZE ? $file->getMaxFilesize() / 1024 : 0; $message = isset($errors[$errorCode]) ? $errors[$errorCode] : 'The file "%s" was not uploaded due to an unknown error.'; return sprintf($message, $file->getClientOriginalName(), $maxFilesize); }
/** * {@inheritdoc} */ public function handleUpload(UploadedFile $file) { $this->prepareTemporaryUploadDestination(); $error = $file->getError(); if ($error != UPLOAD_ERR_OK) { // Check for file upload errors and return FALSE for this file if a lower // level system error occurred. For a complete list of errors: // See http://php.net/manual/features.file-upload.errors.php. switch ($error) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $message = t('The file could not be saved because it exceeds the maximum allowed size for uploads.'); continue; case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_FILE: $message = t('The file could not be saved because the upload did not complete.'); continue; // Unknown error. // Unknown error. default: $message = t('The file could not be saved. An unknown error has occurred.'); continue; } throw new UploadException(UploadException::FILE_UPLOAD_ERROR, $message); } // Open temp file. $tmp = "{$this->temporaryUploadLocation}/{$this->getFilename($file)}"; if (!($out = fopen($tmp, $this->request->request->get('chunk', 0) ? 'ab' : 'wb'))) { throw new UploadException(UploadException::OUTPUT_ERROR); } // Read binary input stream. $input_uri = $file->getFileInfo()->getRealPath(); if (!($in = fopen($input_uri, 'rb'))) { throw new UploadException(UploadException::INPUT_ERROR); } // Append input stream to temp file. while ($buff = fread($in, 4096)) { fwrite($out, $buff); } // Be nice and keep everything nice and clean. // @todo when implementing multipart don't forget to drupal_unlink. fclose($in); fclose($out); return $tmp; }