### app binding : xe.storage 으로 바인딩 되어 있음
Storage Facade 로 접근이 가능
### 파일 저장
업로드된 파일을 저장하는 경우 Request 에서 반환하는
Symfony\Component\HttpFoundation\File\UploadedFile 객체를 전달 해야 합니다.
php
$uploadFile = Input::file('file');
Storage::upload($uploadFile, 'dir/path');
업로드 되는 파일의 이름을 별도로 지정하고 싶은 경우 3번째 인자로
지정하고 싶은 이름을 넣어 주면 됩니다.
php
Storage::upload($uploadFile, 'dir/path', 'new_name');
저장되는 저장소를 지정하고 싶은 경우 4번째 인자로
config 에 설정된 저장소 중 하나를 함께 전달 하면 됩니다.
php
Storage::upload($uploadFile, 'dir/path', 'new_name', 's3');
file content 를 직접 저장시킬 수 도 있습니다.
이때는 create 메서드를 사용합니다.
$content = file_get_content('path/to/file');
Storage::create($content, 'dir/path', 'filename');
또한 create 메서드를 통해 부모 자식관계를 형성할 수 있습니다.
이때는 5번째 인자로 부모에 해당하는 파일의 아이디를 전달하면 됩니다.
php
Storage::create($content, 'dir/path', 'filename', null, 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx');
### 다운로드
다운로드 시에는 download 메서드에 파일객체를 전달하면 됩니다.
이때 다운로드 되는 파일명을 변경하고자 하는 경우 변경할 이름도 함께 전달해야합니다.
Storage::download($file, 'new_filename');
### 연결
Storage 는 특정 대상이 파일을 소유하는 형태가 아닌
파일을 특정대상과 연결하는 방식으로 제공 됩니다.
특정 대상으로 부터 파일 업로드 후 연결 처리를 하기위해 다음과 같이 사용해야 합니다.
php
$uploadFile = Input::file('file');
$file = Storage::upload($file, 'dir/path');
Storage::bind('target id', $file);
연결을 끊는 동작은 unBind를 이용합니다.
php
Storage::unBind('target id', $file);
이때 파일에 연결된 대상이 더이상 존재하지 않는 경우 삭제를 원한다면
삭제처리를 하도록 추가 정보를 전달합니다.
php
Storage::unBind('target id', $file, true);
/** * Create thumbnail images * * @param string $origin image content * @param CommandInterface $command executable command * @param null|string $code dimension code * @param null|string $disk storage disk * @param null|string $path saved path * @param null|string $originId origin file id * @return Image */ public function createThumbnails($origin, CommandInterface $command, $code = null, $disk = null, $path = null, $originId = null) { $thumbnailer = $this->makeThumbnailer(); $content = $thumbnailer->setOrigin($origin)->addCommand($command)->generate(); $file = $this->storage->create($content, $path ?: '', implode('_', [$command->getName(), $command->getDimension()->getWidth() . 'x' . $command->getDimension()->getHeight(), hash('sha1', $content)]), $disk, $originId); return $this->make($file, ['type' => $command->getName(), 'code' => $code]); }
public function destroy() { $ids = Input::get('id'); $files = $this->storage->getsIn($ids); foreach ($files as $file) { $this->storage->remove($file); } if (Input::get('redirect') != null) { return redirect(Input::get('redirect')); } else { return redirect()->route('manage.storage.index'); } }
/** * 회원의 프로필 이미지를 등록한다. * * @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; }
/** * 문서 삭제 * * @param ItemEntity $item board item entity * @param ConfigEntity $config destination board config entity * @return int */ public function remove(ItemEntity $item, ConfigEntity $config) { $item = $this->get($item->id, $item->instanceId); // 덧글이 있다면 덧글들을 모두 휴지통으로 옯긴다. $count = 0; if ($config->get('recursiveDelete') === true) { $rows = $this->document->getRepository()->getReplies($item->getDocument()); foreach ($rows as $row) { $item = $this->get($row['id'], $row['instanceId']); $count = $this->document->remove($item->getDocument()); $this->slug->delete($item->getSlug()); /** @var \Xpressengine\Storage\File $file */ foreach ($this->storage->getsByTargetId($item->id) as $file) { $this->storage->unBind($item->id, $file, true); } } } else { $count = $this->document->remove($item->getDocument()); $this->slug->delete($item->getSlug()); /** @var \Xpressengine\Storage\File $file */ foreach ($this->storage->getsByTargetId($item->id) as $file) { $this->storage->unBind($item->id, $file, true); } } return $count; }
/** * Extract file meta data * * @param File $file file instance * @return Meta */ protected function extractInformation(File $file) { $content = $this->storage->read($file); list($realWidth, $realHeight) = getimagesizefromstring($content); $meta = new Meta(); $meta->id = $file->getId(); $meta->originId = $file->getOriginId(false); $meta->width = $realWidth; $meta->height = $realHeight; return $meta; }
/** * 회원의 프로필 이미지를 등록한다. * * @param MemberEntityInterface $member 프로필 이미지를 등록할 회원 * @param UploadedFile $profileFile 프로필 이미지 파일 * * @return string 등록한 프로필이미지 ID */ public function updateMemberProfileImage(MemberEntityInterface $member, UploadedFile $profileFile) { $disk = array_get($this->profileImgConfig, 'storage.disk'); $path = array_get($this->profileImgConfig, 'storage.path'); $size = array_get($this->profileImgConfig, 'size'); // make fitted imageg /** @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 ($member->profileImageId !== null && $member->profileImageId !== "") { $file = $this->storage->get($member->profileImageId); $this->storage->remove($file); } $id = $member->getId(); // save image to storage $file = $this->storage->create($image->encode()->getEncoded(), $path . "/{$id}", $id, $disk); return $file->getId(); }
/** * Get files of target used * * @param string $targetId target identifier * @return File[] */ public function getFiles($targetId) { $data = []; $fileClass = $this->storage->getModel(); $files = $fileClass::getByFileable($targetId); foreach ($files as $file) { $thumbnails = null; if ($this->mediaManager->is($file)) { $imgClass = $this->mediaManager->getHandler(Media::TYPE_IMAGE)->getModel(); $thumbnails = $imgClass::getThumbnails($this->mediaManager->make($file), static::THUMBNAIL_TYPE); } $file->setRelation('thumbnails', $thumbnails); $data[] = $file; } return $data; }
/** * Extract file meta data * * @param File $file file instance * @return Meta */ protected function extractInformation(File $file) { $meta = new Meta(); $meta->id = $file->getId(); $meta->originId = $file->getOriginId(false); $tmpPathname = $this->temp->getTempPathname(); $this->temp->createFile($tmpPathname, $this->storage->read($file)); $info = $this->reader->analyze($tmpPathname); $this->temp->remove($tmpPathname); if (isset($info['audio']['streams'])) { unset($info['audio']['streams']); } $meta->audio = $info['audio']; $meta->playtime = $info['playtime_seconds']; $meta->bitrate = $info['bitrate']; return $meta; }
/** * 문서 삭제 * * @param Board $board board model * @param ConfigEntity $config board config entity * @return void * @throws \Exception */ public function remove(Board $board, ConfigEntity $config) { $board->getConnection()->beginTransaction(); // 덧글이 있다면 덧글들을 모두 삭제 if ($config->get('recursiveDelete') === true) { $query = Board::where('head', $board->head); if ($board->reply !== '' && $board->reply !== null) { $query->where('reply', 'like', $board->reply . '%'); } $items = $query->get(); foreach ($items as $item) { $this->setModelConfig($item, $config); if ($item->boardSlug !== null) { $item->boardSlug->delete(); } if ($item->boardCategory !== null) { $item->boardCategory->delete(); } $files = File::whereIn('id', $item->getFileIds())->get(); foreach ($files as $file) { $this->storage->unBind($item->id, $file, true); } $tags = Tag::getByTaggable($item->id); foreach ($tags as $tag) { $tag->delete(); } $item->delete(); } } else { if ($board->slug !== null) { $board->slug->delete(); } $files = File::whereIn('id', $board->getFileIds())->get(); foreach ($files as $file) { $this->storage->unBind($board->id, $file, true); } $tags = Tag::getByTaggable($board->id); foreach ($tags as $tag) { $tag->delete(); } $board->delete(); } $board->getConnection()->commit(); }
/** * 미디어 삭제 * * @param Media $media media instance * @return bool */ public function remove(Media $media) { $this->metaRemove($media); return $this->storage->remove($media); }
/** * Set site representative image * * @param Image $image image instance * @return void */ public function setSiteImage(Image $image) { $this->storage->removeAll($this->get('uuid')); $this->storage->bind($this->get('uuid'), $image->getFile()); $this->image = $image; }
/** * file destory * * @param Storage $storage * @param string $instanceId * @param string $id * @return RendererInterface */ public function fileDestroy(Storage $storage, $instanceId, $id) { if (empty($id) || !($file = File::find($id))) { throw new InvalidArgumentException(); } if ($file->userId !== Auth::id()) { throw new AccessDeniedHttpException(); } try { $result = $storage->remove($file); } catch (\Exception $e) { $result = false; } return XePresenter::makeApi(['deleted' => $result]); }
public function testUnBindNotRemovedFileWhenFlagFalse() { list($handler, $auth, $keygen, $distributor, $temps) = $this->getMocks(); $instance = new Storage($handler, $auth, $keygen, $distributor, $temps); $mockFile = m::mock('Xpressengine\\Storage\\File'); $mockConn = m::mock('stdClass'); $mockFile->shouldReceive('getConnection')->andReturn($mockConn); $mockFile->shouldReceive('getFileableTable')->andReturn('fileable_table'); $mockFile->shouldReceive('getKey')->andReturn('file-id'); $mockConn->shouldReceive('table')->once()->with('fileable_table')->andReturnSelf(); $mockConn->shouldReceive('where')->once()->with('fileId', 'file-id')->andReturnSelf(); $mockConn->shouldReceive('where')->once()->with('fileableId', 'fileable-id')->andReturnSelf(); $mockConn->shouldReceive('delete')->once()->andReturn(1); $mockFile->shouldReceive('getAttribute')->with('useCount')->andReturn(1); $mockFile->shouldReceive('setAttribute')->once()->with('useCount', 0)->andSet('useCount', 0); $mockFile->shouldReceive('save')->andReturn(true); $instance->unBind('fileable-id', $mockFile); }
/** * Set site representative image * * @param Image $image image instance * @return void */ public function setSiteImage(Image $image) { $this->storage->unBindAll($this->get('uuid')); $this->storage->bind($this->get('uuid'), $image); $this->image = $image; }
public function testCountByMime() { list($handler, $repo, $auth, $keygen) = $this->getMocks(); $instance = new Storage($handler, $repo, $auth, $keygen); $repo->shouldReceive('countGroupBy')->andReturn(10); $this->assertEquals(10, $instance->countByMime()); }