Ejemplo n.º 1
2
 /**
  * Handles an uploaded file by putting it in the $targetDir.
  * 
  * @param UploadedFile $uploadedFile File object that has been uploaded - usually taken from Request object.
  * @param string $targetDir [optional] Where to (relatively to the storage root dir) put the file?
  * @param array $allowed [optional] What files are allowed? If not matching then will throw exception.
  * @param int $maxFileSize [optional] What is the maximum allowed file size for this file?
  * @return File
  */
 public function handleUploadedFile(UploadedFile $uploadedFile, $targetDir = '/', array $allowed = array(), $maxFileSize = 0)
 {
     array_walk($allowed, function ($ext) {
         return strtolower($ext);
     });
     $targetDir = trim($targetDir, '/');
     $targetDir = $this->path . $targetDir . (empty($targetDir) ? '' : '/');
     $filenameElements = explode('.', $uploadedFile->getClientOriginalName());
     $extension = array_pop($filenameElements);
     $extension = strtolower($extension);
     $filename = implode('.', $filenameElements);
     $targetName = StringUtils::fileNameFriendly($filename . '-' . StringUtils::random() . '.' . $extension);
     $targetPath = $targetDir . $targetName;
     // create unique file name
     while (file_exists($targetPath)) {
         $targetName = StringUtils::fileNameFriendly($filename . '-' . StringUtils::random() . '.' . $extension);
         $targetPath = $targetDir . $targetName;
     }
     // basic check for allowed type
     if (!empty($allowed) && !in_array($extension, $allowed)) {
         throw new FileException('The uploaded file is not of a valid type (allowed: ' . implode(', ', $allowed) . ').');
     }
     // basic check for max allowed size
     if ($maxFileSize && $uploadedFile->getSize() > $maxFileSize) {
         throw new FileException('The uploaded file is too big (max allowed size is ' . StringUtils::bytesToString($maxFileSize) . ').');
     }
     try {
         $movedFile = $uploadedFile->move(rtrim($targetDir, '/'), $targetName);
     } catch (SfFileException $e) {
         // if exception thrown then convert it to our exception
         throw new FileException($e->getMessage(), $e->getCode());
     }
     $file = $this->convertSfFileToStorageFile($movedFile);
     return $file;
 }
Ejemplo n.º 2
1
 /**
  * {@inheritdoc}
  *
  * @param null|\Symfony\Component\HttpFoundation\File\UploadedFile $data
  */
 public function convertFieldValueFromForm($data)
 {
     if ($data === null) {
         return null;
     }
     return array("inputUri" => $data->getRealPath(), "fileName" => $data->getClientOriginalName(), "fileSize" => $data->getSize());
 }
Ejemplo n.º 3
1
 /**
  * {@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;
 }
Ejemplo n.º 4
0
 /**
  * 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;
     }
 }
Ejemplo n.º 5
0
 /**
  * Execute the job.
  */
 public function handle()
 {
     /**
      * Create Extra
      * @var Extra $extra
      */
     $extra = $this->product->extras()->create($this->data);
     $aspectDir = @$this->data['aspect_ratio'] ?: '16x9';
     /**
      * Move Extra Content to folder
      */
     $path = '/image/products-extras/';
     $extraID = $extra->getAttribute('id');
     $productCode = $this->product->getAttribute('code');
     $filename = $productCode . '-extra-image-' . $extraID . '.' . $this->image->guessExtension();
     $image = $this->image->move(base_path() . $path, $filename);
     $extra->setAttribute('image', $path . $filename);
     $filename = $productCode . '-extra-video-' . $extraID . '.' . $this->video->guessExtension();
     $video = $this->video->move(base_path() . $path . $aspectDir . '/', $filename);
     $extra->setAttribute('video', $filename);
     $extra->save();
     /**
      * Announce ExtraWasCreated
      */
     event(new ExtraWasCreated($extra));
 }
Ejemplo n.º 6
0
 public function saveUserUploadedPhoto(UploadedFile $file)
 {
     $extension = CommonFunction::getFileExtension($file->getClientOriginalName());
     $fileName = md5(microtime(true)) . '.' . $extension;
     $file->move($this->getUserPhotoDir(), $fileName);
     return $fileName;
 }
Ejemplo n.º 7
0
 /**
  * 회원의 프로필 이미지를 등록한다.
  *
  * @param UserInterface $user        프로필 이미지를 등록할 회원
  * @param UploadedFile  $profileFile 프로필 이미지 파일
  *
  * @return string 등록한 프로필이미지 ID
  */
 public function updateUserProfileImage(UserInterface $user, UploadedFile $profileFile)
 {
     $disk = array_get($this->profileImgConfig, 'storage.disk');
     $path = array_get($this->profileImgConfig, 'storage.path');
     $size = array_get($this->profileImgConfig, 'size');
     // make fitted image
     /** @var ImageManager $imageManager */
     $imageManager = call_user_func($this->imageManagerResolver);
     $image = $imageManager->make($profileFile->getRealPath());
     $image = $image->fit($size['width'], $size['height']);
     // remove old profile image
     if (!empty($user->profileImageId)) {
         $file = File::find($user->profileImageId);
         if ($file !== null) {
             try {
                 $this->storage->remove($file);
             } catch (\Exception $e) {
             }
         }
     }
     // save image to storage
     $id = $user->getId();
     $file = $this->storage->create($image->encode()->getEncoded(), $path . "/{$id}", $id, $disk);
     return $file->id;
 }
Ejemplo n.º 8
0
 public function moveUploadedFile(UploadedFile $file, $uploadBasePath, $relativePath, $fileName)
 {
     $originalName = $file->getFilename();
     // use filemtime() to have a more determenistic way to determine the subpath, otherwise its hard to test.
     // $relativePath = date('Y-m', filemtime($file->getPath()));
     $targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;
     $targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;
     $ext = $file->getExtension();
     $i = 1;
     while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
         if ($ext) {
             $prev = $i == 1 ? "" : $i;
             $targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);
         } else {
             $targetFilePath = $targetFilePath . $i++;
         }
     }
     $targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath;
     if (!is_dir($targetDir)) {
         $ret = mkdir($targetDir, umask(), true);
         if (!$ret) {
             throw new \RuntimeException("Could not create target directory to move temporary file into.");
         }
     }
     //$file->move($targetDir, basename($targetFilePath));
     //$file->move($targetDir, basename($fileName.'.'.$ext));
     $file->move($targetDir, basename($fileName));
     return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
 }
Ejemplo n.º 9
0
 public function getFileMd5Name(UploadedFile $file)
 {
     $ext = $file->guessExtension();
     $md5 = md5_file($file->getRealPath());
     $name = $md5 . '.' . $ext;
     return $name;
 }
Ejemplo n.º 10
0
 /**
  * @param UploadedFile $uploadedFile
  */
 function upload(UploadedFile $uploadedFile)
 {
     $path = sha1(uniqid(mt_rand(), true)) . '.' . $uploadedFile->guessExtension();
     $this->setPath($path);
     $this->setName($uploadedFile->getClientOriginalName());
     $uploadedFile->move($this->getUploadRootDir(), $path);
 }
Ejemplo n.º 11
0
 /**
  * @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;
 }
Ejemplo n.º 12
0
 private function saveDisc(UploadedFile $file)
 {
     $fileName = time() . $file->getClientOriginalName();
     $path = 'foto/';
     $file->move($path, $fileName);
     return $fileName;
 }
Ejemplo n.º 13
0
 /**
  * The main upload method.
  * 
  * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file Uploaded file instance.
  * @return string
  */
 public function upload(\Symfony\Component\HttpFoundation\File\UploadedFile $file)
 {
     // We simply move the uploaded file to the target directory
     $result = $file->move(\Config::get('plupload::plupload.upload_dir'), $file->getClientOriginalName());
     // Return the result of the upload
     return $this->respond(array('OK' => $result ? 1 : 0));
 }
Ejemplo n.º 14
0
 /**
  * Converts UploadedFile of users into array of User objects
  *
  * @param UploadedFile $file
  * @return array
  */
 public function parseUserFile(UploadedFile $file)
 {
     $data = array('users' => array(), 'columns' => array());
     switch ($file->getClientOriginalExtension()) {
         case 'csv':
             $file = $file->openFile();
             $data['columns'] = $file->fgetcsv();
             while (!$file->eof()) {
                 $user = new User();
                 $row = $file->fgetcsv();
                 if (array(null) == $row) {
                     continue;
                 }
                 foreach ($row as $key => $userProperty) {
                     $functionName = 'set' . ucfirst($data['columns'][$key]);
                     if (!method_exists($user, $functionName)) {
                         throw new MappingException('User has no property ' . $data['columns'][$key]);
                     }
                     $user->{$functionName}($userProperty);
                 }
                 $this->isUserValid($user);
                 $data['users'][] = $user;
             }
             break;
     }
     return $data;
 }
Ejemplo n.º 15
0
 /**
  * Move uploaded images to its destination path
  * @param  UploadedFile $file
  * @return $this
  */
 public function move(UploadedFile $file)
 {
     $file->move($this->baseDir, $this->name);
     $this->makeThumbnail();
     $this->makeIcon();
     return $this;
 }
Ejemplo n.º 16
0
 protected function savePhoto(UploadedFile $photo)
 {
     $fileName = str_random(40) . '.' . $photo->guessClientExtension();
     $destinationPath = public_path() . '/upload/gambar/';
     $photo->move($destinationPath, $fileName);
     return $fileName;
 }
Ejemplo n.º 17
0
 /**
  * {@inheritdoc}
  */
 public function canUpload(UploadedFile $file)
 {
     if ($file->getMimeType() == 'text/plain' && $file->getClientOriginalExtension() == 'md') {
         return 5;
     }
     return 0;
 }
Ejemplo n.º 18
0
 public function upload(UploadedFile $file)
 {
     if ($file->isValid()) {
         $name = $file->getClientOriginalName();
         $size = $file->getClientSize();
     }
 }
Ejemplo n.º 19
0
 /**
  * Upload a new resource.
  *
  * @param UploadedFile $file
  * @return string
  */
 public function uploadResource(UploadedFile $file)
 {
     $destination_path = public_path('uploads' . DIRECTORY_SEPARATOR);
     $file_name = $this->generatePath($file->getClientOriginalName());
     $file->move($destination_path, $file_name);
     return $file_name;
 }
Ejemplo n.º 20
0
 /**
  * Generate a proper filename.
  *
  * @param UploadedFile $file
  * @return bool|string
  */
 private function getFilename(UploadedFile $file)
 {
     $path = $file->getClientOriginalName();
     $path .= '_' . dechex(time());
     $path .= '.' . $file->getClientOriginalExtension();
     return $path;
 }
Ejemplo n.º 21
0
 public function upload(UploadedFile $file, PropertyMapping $propertyMapping, $filter_name = NULL)
 {
     if ($filter_name === NULL) {
         $filter_name = $propertyMapping->getMappingName();
     }
     // vars
     $provider = $this->getProvider($propertyMapping);
     $filesystem = $provider->getFilesystem();
     $relative_dir = $provider->getRelativeDir();
     //$propertyMapping->getUriPrefix();
     $file_name = $file->getClientOriginalName();
     // if namer set
     $mapping_config = $this->vichGetMappingConfig($propertyMapping->getMappingName());
     if ($mapping_config) {
         $namer = $mapping_config['namer'];
         // illegal offset warning (backwards compatibility)
         if (is_array($namer) && isset($namer['service'])) {
             $namer = $namer['service'];
         }
         if ($this->getContainer()->has($namer)) {
             $namer = $this->getContainer()->get($namer);
             if (method_exists($namer, 'getRandomFileName')) {
                 $file_name = $namer->getRandomFileName($file_name, $propertyMapping);
             }
         }
     }
     // upload
     $uploaded = $filesystem->write($relative_dir . '/' . $file_name, file_get_contents($file->getPathname()));
     //$uploaded = $file->move($upload_dir, $file_name);
     if ($uploaded) {
         // apply filter
         return $this->doApplyFilter($file_name, $propertyMapping);
     }
     return false;
 }
Ejemplo n.º 22
0
 /**
  * Save file to folder.
  *
  * @author Casper Rasmussen <*****@*****.**>
  *
  * @param  \Symfony\Component\HttpFoundation\File\UploadedFile $uploadedFile
  * @param  \Nodes\Assets\Upload\Settings                       $settings
  *
  * @return string
  * @throws \Nodes\Assets\Upload\Exceptions\AssetsUploadFailedException
  */
 protected function store(UploadedFile $uploadedFile, Settings $settings)
 {
     // Fallback folder is none is set
     if (!$settings->hasFolder()) {
         $settings->setFolder('default');
     }
     try {
         // Retrieve folder path
         $path = public_path(config('nodes.assets.providers.publicFolder.subFolder')) . DIRECTORY_SEPARATOR . $settings->getFolder();
         // If folder doesn't exists,
         // we'll create it with global permissions
         if (!file_exists($path)) {
             mkdir($path, 0777, true);
         }
         // Stream uploaded file
         $content = file_get_contents($uploadedFile->getPathname());
         // Save uploaded file to folder
         $result = file_put_contents($path . DIRECTORY_SEPARATOR . $settings->getFileName() . '.' . $settings->getFileExtension(), $content);
         if (!$result) {
             throw new NodesException('Failed to save', 500);
         }
     } catch (Exception $e) {
         throw new AssetsUploadFailedException('Could not save the file to public folder. Reason: ' . $e->getMessage());
     }
     return $settings->getFilePath();
 }
Ejemplo n.º 23
0
 /**
  * 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;
 }
 public function upload(UploadedFile $file, $folder)
 {
     $path = $this->path . $folder . '/';
     $name = md5(uniqid(rand(), 1)) . '.' . $file->getClientOriginalExtension();
     $file->move($path, $name);
     return url('img', [$folder, $name]);
 }
Ejemplo n.º 25
0
 /**
  * {@inheritDoc}
  */
 protected function doUpload(PropertyMapping $mapping, UploadedFile $file, $dir, $name)
 {
     $fs = $this->getFilesystem($mapping);
     $path = !empty($dir) ? $dir . '/' . $name : $name;
     $stream = fopen($file->getRealPath(), 'r+');
     $fs->writeStream($path, $stream, array('mimetype' => $file->getMimeType()));
 }
Ejemplo n.º 26
0
 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;
 }
Ejemplo n.º 27
0
 public static function upload(UploadedFile $file)
 {
     $fileMedia = new static();
     $file->name = time() . '_' . strtolower($file->getClientOriginalName());
     $file->move(config('admin.fileUploadDirectory'), $file->name);
     return $file;
 }
Ejemplo n.º 28
0
 /**
  * Saving and Database Recording Users Default Picture
  * @param UploadedFile $file Library for Uploading Files Locally or Cloud
  * @param User         $user Users Model
  */
 public function UserProfilePicture(UploadedFile $file, User $user)
 {
     $Image = $file->getClientOriginalName();
     $Imagename = 'DP_' . $Image;
     $file->move(\Auth::User()->username . '/profile_images/', $Imagename);
     $user->userData()->update(['profile_picture' => '/' . \Auth::User()->username . '/profile_images/' . $Imagename, 'picture_name' => $Imagename]);
 }
Ejemplo n.º 29
0
 public static function save($path, UploadedFile $file)
 {
     $ext = substr(strrchr($file->getClientOriginalName(), '.'), 1);
     $new_name = md5(time() . rand()) . '.' . $ext;
     $file->move($path, $new_name);
     return $new_name;
 }
Ejemplo n.º 30
0
 /**
  * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file
  *
  * @return string
  */
 protected function uploadSingleFile($file)
 {
     $filename = uniqid() . '.' . $file->getClientOriginalExtension();
     $targetDirectory = public_path($this->config->get('paxifi.files.uploads_directory'));
     $file->move($targetDirectory, $filename);
     return $this->config->get('app.url') . '/' . basename($targetDirectory) . '/' . $filename;
 }