public function execute() { if ($this->photo->isValid()) { $name = sha1($this->user->getId() . $this->user->getLogin() . $this->user->getRegisteredAt() . time() . uniqid('ffdf')); $photoUploader = new PhotoFormatter($this->photo->getRealPath(), self::MINIMUM_SIZE, self::MAXIMUM_SIZE, $this->output); $old = $this->user->getAvatar(); $photoUploader->setNewName($name); $photoUploader->loadAndScale(self::START_SIZE); $this->user->setAvatar($name); $this->repository->update($this->user); if (!empty($old)) { $photoUploader->removeOld($old, self::START_SIZE); } } }
protected function upload(UploadedFile $file, $oldFile) { $list = ""; // foreach($files as $file) // { // $validator = Validator::make( array('file' => $file) , array('file' => array($this->Rule) ) ); // // if($validator->fails()) // { //laravel內建的驗證無法使用(可能是bug吧),所以自己寫一個 foreach ($this->Rule as $rule) { if ($file->getClientOriginalExtension() == $rule) { if ($file->isValid()) { if ($this->groupno != "") { $year = substr($this->groupno, 1, 3); $destinationPath = public_path() . '/upload/' . $year . '/' . $this->groupno; } else { $destinationPath = public_path() . '/upload/teacher'; } $fileName = $file->getClientOriginalName(); File::delete($destinationPath . '/' . $oldFile); $file->move($destinationPath, $fileName); //用 "|" 隔開檔名 $list .= $fileName . "|"; } } } // } // } $list = substr($list, 0, -1); return $list; }
/** * @param UploadedFile|null $uploadedFile * @param array $options * @return AssetFile */ public function handleUpload(UploadedFile $uploadedFile = null, array $options = []) { $resolver = new OptionsResolver(); $resolver->setDefaults(['type' => null, 'fallbackType' => null, 'targetUri' => null])->setAllowedTypes(['type' => ['string', 'null'], 'fallbackType' => ['int', 'null'], 'targetUri' => ['string', 'null']])->setAllowedValues(['type' => ['image', 'audio', 'file', null]]); $options = $resolver->resolve($options); if (!$uploadedFile instanceof UploadedFile || !$uploadedFile->isValid() || !($assetFile = new AssetFile($uploadedFile, null, $options['fallbackType'])) || $assetFile->getType() === null) { throw new \RuntimeException('Invalid uploaded file'); } $assetFile->setOriginalName($uploadedFile->getClientOriginalName()); if ($options['type'] !== null) { $this->validateAssetFileType($assetFile, $options['type']); } if ($options['targetUri'] !== null) { $uploadsDir = $this->assetsResolver->uriToPath($options['targetUri']); } else { $uploadsDir = $this->assetsResolver->assetPath($assetFile->getType()); } $tempFile = $uploadedFile->move($uploadsDir, $this->getTargetFileName($uploadedFile->getClientOriginalName(), $uploadsDir)); $assetFile->setFile($tempFile); $uri = $this->assetsResolver->pathToUri($assetFile->getFile()->getPathname()); if ($uri === null) { throw new \RuntimeException('Unable to retrieve uploaded file uri'); } $assetFile->setUri($uri); return $assetFile; }
/** * @param string|array|UploadedFile $data * * @return bool */ protected function isFileUpload($data) { if ($data instanceof UploadedFile) { return $data->isValid() && $data->getClientSize() > 0; } return is_array($data) && !empty($data['tmp_name']) && !empty($data['size']) && $data['error'] === UPLOAD_ERR_OK; }
public static function upload(UploadedFile $file, $bucketName) { if (!$file->isValid()) { throw new \Exception(trans('validation.invalid_file')); } $bucket = Bucket::find($bucketName); if (!empty($bucket->mimeTypes()) && !in_array($file->getMimeType(), $bucket->mimeTypes())) { throw new \Exception(trans('validation.invalid_file_type')); } if (!empty($bucket->maxSize()) && !in_array($file->getClientSize(), $bucket->maxSize())) { throw new \Exception(trans('validation.invalid_file_size')); } $disk = Storage::disk($bucket->disk()); $media = Media::create(['mime' => $file->getMimeType(), 'bucket' => $bucketName, 'ext' => $file->guessExtension()]); $disk->put($bucket->path() . '/original/' . $media->fileName, File::get($file)); if (is_array($bucket->resize())) { foreach ($bucket->resize() as $name => $size) { $temp = tempnam(storage_path('tmp'), 'tmp'); Image::make(File::get($file))->fit($size[0], $size[1])->save($temp); $disk->put($bucket->path() . '/' . $name . '/' . $media->fileName, File::get($temp)); unlink($temp); } } return $media; }
/** * Put and save a file in the public directory * * @param string path of the file * @return mixed keypath of file or false if error occurred during uploading */ public static function putUploadedFile(UploadedFile $file) { if ($file->isValid()) { //Remove all the slashes that doesn't serve FileStorage::clearPublicStartPath(); //Retrive and save the file extension of the file uploaded $fileExtension = $file->getClientOriginalExtension(); //Save the public path with the start path $absolutePath = public_path() . '/' . FileStorage::$publicStartPath; //Generate a random name to use for the file uploaded $keyFile = FileStorage::generateKey(FileStorage::$keyLength) . '.' . $fileExtension; //Check if the file with the $keyFile name doesn't exist, else, regenerate it while (file_exists($absolutePath . '/' . ord($keyFile[0]) . '/' . $keyFile)) { $keyFile = FileStorage::generateKey(FileStorage::$keyLength) . '.' . $fileExtension; } //Move the uploaded file and save $file->move($absolutePath . '/' . ord($keyFile[0]), $keyFile); //Save the keypath (start path, sub path, file name) $keyPath = FileStorage::$publicStartPath . '/' . ord($keyFile[0]) . '/' . $keyFile; //Return public path of the file return $keyPath; } else { return false; } }
public function upload(UploadedFile $file) { if ($file->isValid()) { $name = $file->getClientOriginalName(); $size = $file->getClientSize(); } }
/** * Upload file from the request * * @param UploadedFile $file * @return Array $data Retrieve into the content of response * @throws BadRequestHttpException The file is too big */ private function doRequestUpload(UploadedFile $file) { $tmpDirectory = $this->getApplication()->getTemporaryDir(); $data = []; if (null !== $file) { if ($file->isValid()) { if ($file->getClientSize() <= $file->getMaxFilesize()) { $data = $this->buildData($file->getClientOriginalName(), $file->guessExtension()); $file->move($tmpDirectory, $data['filename']); $data['size'] = round($file->getClientSize() / 1024, 2); if ($imageInfo = @getimagesize($data['path'])) { if (isset($imageInfo[0]) && isset($imageInfo[1])) { $data['width'] = $imageInfo[0]; $data['height'] = $imageInfo[1]; } } else { $data['width'] = 0; $data['height'] = 0; } } else { throw new BadRequestHttpException('Too big file, the max file size is ' . $file->getMaxFilesize()); } } else { throw new BadRequestHttpException($file->getErrorMessage()); } } return $data; }
/** * @param string $containerName * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @param string|null $relativePath * * @return bool */ public function saveUploadedFile($containerName, UploadedFile $file, $relativePath) { if ($file->isValid() === false) { return false; } $fileName = $file->getClientOriginalName(); $filePath = $this->getFullFileName($containerName, $fileName); return $this->move($file->getRealPath(), $filePath); }
/** * @param UploadedFile $file * * @return Uploader * * @throws UploaderException */ public function init(UploadedFile $file) { // check if file correct if (!$file->isValid()) { throw new UploaderException($file->getErrorMessage()); } $this->file = $file; return $this; }
public function uploadFile(UploadedFile $file, $fileName, $path) { try { if ($file->isValid()) { $file->move($path, $fileName); } } catch (\Exception $ex) { throw $ex; } }
/** * Enregistre un fichier téléchargé en le déplaçant dans le répertoire $upload_directory sous le nom $filename. * On conserve l'extension du fichier d'origine * * @param UploadedFile $file * @param $uploadDirectory * @param $filename * @return bool */ public function saveUploadedFile(UploadedFile $file, $uploadDirectory, $filename) { if (!$file->isValid()) { return false; } $this->upload_directory = $uploadDirectory; $this->filename = $filename . '.' . $file->getClientOriginalExtension(); $file->move($this->upload_directory, $this->filename); return true; }
/** * Constructor. * * @param Application $app * @param string $formName * @param File $file */ public function __construct(Application $app, $formName, UploadedFile $file) { $this->app = $app; $this->formName = $formName; $this->file = $file; $this->fullPath = (string) $file; $this->fileName = basename($this->fullPath); $this->valid = $file->isValid(); $this->config = $app[Extension::CONTAINER]->config; }
/** * Uploads the file * * @param UploadedFile $file * @param $dir * * @return \WellCommerce\AppBundle\Entity\MediaInterface * @throws \Exception */ public function upload(UploadedFile $file, $dir) { $uploadPath = $this->getUploadRootDir($dir); if (!$file->isValid()) { throw new \Exception('Passed file object is not valid'); } $media = $this->createMediaFromUploadedFile($file); $this->saveResource($media); $file->move($uploadPath, $media->getPath()); return $media; }
/** * Constructor. * * @param Application $app * @param string $formName * @param File $file */ public function __construct(Application $app, $formName, UploadedFile $file) { $this->app = $app; $this->formName = $formName; $this->file = $file; $this->fullPath = (string) $file; $this->fileName = basename($this->fullPath); $this->valid = $file->isValid(); $extension = $app['extensions']->get('Bolt/BoltForms'); $this->config = $extension->getConfig(); }
/** * コンストラクタ */ public function __construct(UploadedFile $objFile) { $this->initialize(); if ($objFile->isValid() == false) { throw new \Exception('File upload is failed.'); } $this->file = $objFile; $this->ext = $objFile->getClientOriginalExtension(); $this->dt = new DateTime(); $this->err = ""; }
/** * Generate image * * @param UploadedFile $file * @param string $fileName * * @return string */ private static function createImage(UploadedFile $file, $fileName = '') { // Get default upload path $uploadPath = Config::get('image.path'); if (!$fileName) { $fileName = $file->getClientOriginalName(); } if ($file->isValid()) { // Upload file to path $saveFullPath = $uploadPath . $fileName; Image::make($file)->save($saveFullPath); return $saveFullPath; } }
/** * @param UploadedFile $uploaded_file * @return array Uploaded file info * @throws FileManagerException */ public function upload(UploadedFile $uploaded_file) { if ($uploaded_file->isValid()) { $file = $this->file->uploading($uploaded_file); $this->uniqueName->file($file); $uploaded_file->move($file->dirPath(), $file->fullName()); if ($file->isImage()) { $this->thumb->create($file); $file->setFileThumb(); } return (array) $file->details(); } throw new FileManagerException($this, 'err_file_upload_invalid_file'); }
/** * Uploads the file * * @param UploadedFile $file * @param $dir * * @return \WellCommerce\Bundle\MediaBundle\Entity\MediaInterface * @throws \Exception */ public function upload(UploadedFile $file, $dir) { $uploadPath = $this->getUploadRootDir($dir); if (!$file->isValid()) { throw new InvalidMediaException('Passed file object is not valid'); } $media = $this->createMediaFromUploadedFile($file); $errors = $this->getValidatorHelper()->validate($media); if (0 !== count($errors)) { throw new InvalidMediaException($errors); } $this->saveResource($media); $file->move($uploadPath, $media->getPath()); return $media; }
/** * Save the profile photo * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @return Boolean */ public function savePhoto(UploadedFile $file) { if (!$file->isValid()) { return false; } try { $this->photo = md5_file($file->getRealPath()); $this->save(); Storage::disk()->put($this->photo, file_get_contents($file->getRealPath())); return true; } catch (\Exception $e) { Log::error('Failed saving photo to user\'s profile: ' . $e->getMessage()); return false; } }
protected function validatePdfUpload(array &$form, FormStateInterface &$form_state, UploadedFile $file_upload, $file_field_name) { /** * @var $file_upload \Symfony\Component\HttpFoundation\File\UploadedFile */ if ($file_upload && $file_upload->isValid()) { // Move it to somewhere we know. $uploaded_filename = $file_upload->getClientOriginalName(); // Ensure the destination is unique; we deliberately use managed files, // but they are keyed on file URI, so we can't save the same one twice. $scheme = $this->config('fillpdf.settings')->get('scheme'); $destination = file_destination(FillPdf::buildFileUri($scheme, 'fillpdf/' . $uploaded_filename), FILE_EXISTS_RENAME); // Ensure our directory exists. $fillpdf_directory = FillPdf::buildFileUri($scheme, 'fillpdf'); $directory_exists = file_prepare_directory($fillpdf_directory, FILE_CREATE_DIRECTORY + FILE_MODIFY_PERMISSIONS); if ($directory_exists) { $file_moved = $this->fileSystem->moveUploadedFile($file_upload->getRealPath(), $destination); if ($file_moved) { // Create a File object from the uploaded file. $new_file = File::create([ 'uri' => $destination, 'uid' => $this->currentUser()->id(), ]); $errors = file_validate_extensions($new_file, 'pdf'); if (count($errors)) { $form_state->setErrorByName('upload_pdf', $this->t('Only PDF files are supported, and they must end in .pdf.')); } else { $form_state->setValue('upload_pdf', $new_file); } } else { $form_state->setErrorByName('upload_pdf', $this->t("Could not move your uploaded file from PHP's temporary location to Drupal file storage.")); } } else { $form_state->setErrorByName('upload_pdf', $this->t('Could not automatically create the <em>fillpdf</em> subdirectory. Please create this manually before uploading your PDF form.')); } } else { $form_state->setErrorByName('upload_pdf', $this->t('Your PDF could not be uploaded. Did you select one?')); } }
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; }
/** * Upload file from the request * * @param UploadedFile $file * @return Array $data Retrieve into the content of response * @throws BadRequestHttpException The file is too big */ private function doRequestUpload(UploadedFile $file) { $tmpDirectory = $this->getParameter("kernel.cache_dir"); $data = []; if (null !== $file) { if ($file->isValid()) { if ($file->getClientSize() <= $file->getMaxFilesize()) { $data = $this->buildData($file->getClientOriginalName(), $file->guessExtension()); $file->move($tmpDirectory, $data['filename']); } else { throw new BadRequestHttpException('Too big file, the max file size is ' . $file->getMaxFilesize()); } } else { throw new BadRequestHttpException($file->getErrorMessage()); } } return $data; }
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; }
public static function updateIcon(Application $app, $databox_id, $bit, $switch, UploadedFile $file) { $databox = $app->findDataboxById($databox_id); $statusStructure = $app['factory.status-structure']->getStructure($databox); if (!$statusStructure->hasStatus($bit)) { throw new InvalidArgumentException(sprintf('bit %s does not exists', $bit)); } $status = $statusStructure->getStatus($bit); $switch = in_array($switch, ['on', 'off']) ? $switch : false; if (!$switch) { throw new Exception_InvalidArgument(); } $url = $statusStructure->getUrl(); $path = $statusStructure->getPath(); if ($file->getSize() >= 65535) { throw new Exception_Upload_FileTooBig(); } if (!$file->isValid()) { throw new Exception_Upload_Error(); } self::deleteIcon($app, $databox_id, $bit, $switch); $name = "-stat_" . $bit . "_" . ($switch == 'on' ? '1' : '0') . ".gif"; try { $file = $file->move($app['root.path'] . "/config/status/", $path . $name); } catch (FileException $e) { throw new Exception_Upload_CannotWriteFile(); } $custom_path = $app['root.path'] . '/www/custom/status/'; $app['filesystem']->mkdir($custom_path, 0750); //resize status icon 16x16px $imageSpec = new ImageSpecification(); $imageSpec->setResizeMode(ImageSpecification::RESIZE_MODE_OUTBOUND); $imageSpec->setDimensions(16, 16); $filePath = sprintf("%s%s", $path, $name); $destPath = sprintf("%s%s", $custom_path, basename($path . $name)); try { $app['media-alchemyst']->turninto($filePath, $destPath, $imageSpec); } catch (\MediaAlchemyst\Exception $e) { } $status['img_' . $switch] = $url . $name; $status['path_' . $switch] = $filePath; return true; }
/** * @param object $model * @throws \LogicException * @return null|object */ protected function cropImage($model) { if (false == $this->uploadedFile || false == $this->uploadedFile->isValid()) { return null; } $fileHandle = fopen($this->uploadedFile->getRealPath(), 'rb'); $imageData = stream_get_contents($fileHandle); $imageMime = $this->uploadedFile->getMimeType(); if (!empty($this->cropData)) { $this->cropper->loadImageFromString($imageData); $this->cropper->crop($this->cropData['sx'], $this->cropData['sy'], $this->cropData['sw'], $this->cropData['sh'], $this->cropData['w'], $this->cropData['h']); $imageData = $this->cropper->getCroppedImageAsString($this->fileFormat); $imageMime = 'image/png'; } $this->setMime($imageMime, $model); $this->setSize(strlen($imageData), $model); $this->setName($this->uploadedFile->getClientOriginalName(), $model); $this->setData($imageData, $model); return null; }
/** * Uplaod Image on Storage * * @param File $file * @param $key * * @return string */ function upload_photo_on_storage(File $file, $key) { if (!$file->isValid() || !$key) { return null; } $imageDirectory = 'images/profile'; if (!Storage::has($imageDirectory)) { Storage::makeDirectory($imageDirectory, 0777); } $imageExtension = $file->getClientOriginalExtension(); $imageHashName = $key; $imageFilePath = "app/{$imageDirectory}/{$imageHashName}"; $imageFileAbsolutePath = storage_path($imageFilePath); // resize image $image = Image::make($file->getRealPath())->resize(300, 300, function ($constraint) { // prevent possible upsizing $constraint->aspectRatio(); $constraint->upsize(); })->save($imageFileAbsolutePath); return $image ? $imageFilePath : null; }
/** * 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 UploadedFile $uploadedFile * @return File|string * @throws ValidationException * @throws \Exception */ public function upload(UploadedFile $uploadedFile) { $isImage = in_array($uploadedFile->getClientOriginalExtension(), ['jpg', 'jpeg', 'bmp', 'png', 'gif', 'svg']); $validationRules = ['max:' . $this->model->getMaxFilesize()]; if ($isImage) { $validationRules[] = 'mimes:jpg,jpeg,bmp,png,gif,svg'; } $validation = \Validator::make(['file_data' => $uploadedFile], ['file_data' => $validationRules]); if ($validation->fails()) { throw new ValidationException($validation); } if (!$uploadedFile->isValid()) { throw new \Exception('File is not valid'); } $file = $this->model->newInstance(); $file->data = $uploadedFile; $file->is_public = true; $file->save(); $file->thumb = $file->getThumb(150, 150); return $file; }
/** * Stores an uploaded file to the storage and update a Picture document for this picture * (no persistence only file creation) * * @param Picture $pub * @param UploadedFile $picFile * * @throws \InvalidArgumentException Bad mimetype */ public function insertUpload(Picture $pub, UploadedFile $picFile) { if (!$picFile->isValid()) { throw new \RuntimeException('Upload was incomplete'); } $serverMimeType = $picFile->getMimeType(); $nick = $pub->getAuthor()->getNickname(); $extension = []; if (!preg_match(self::MIMETYPE_REGEX, $serverMimeType, $extension)) { throw new \InvalidArgumentException($serverMimeType . ' is not a valid mime type'); } $syntheticName = $this->hashForNick($nick) . '.' . $extension[1]; $pub->setMimeType($serverMimeType); $pub->setStorageKey($syntheticName); $path = $this->getStoragePath($syntheticName); // because diskspace is costly, I don't want to keep original picture // that's why I resize & recompress at a full-hd res (mobile first and I don't intend to // clone Picasa) Image::open($picFile->getPathname())->setCacheDir($this->cacheDir)->cropResize($this->sizeConfig[self::MAX_RES], $this->sizeConfig[self::MAX_RES])->save($path); if (!file_exists($path)) { throw new \RuntimeException("Cannot save {$syntheticName}"); } $pub->setFileSize(filesize($path)); }