public function uploadAction() { $renderer = $this->getServiceLocator()->get('Zend\\View\\Renderer\\RendererInterface'); $fileDirectory = new DirectoryIterator(self::PATH_IMAGES); $adapter = new Http(); $adapter->setDestination(implode(DIRECTORY_SEPARATOR, [self::PATH_IMAGES, FileProperties::DIR_RAW])); $result = ['media' => [], 'length' => $this->requestContentLength($this->getRequest())]; foreach ($adapter->getFileInfo() as $info) { $originalFileName = $info['name']; $uploadedFileObject = new SplFileInfo(implode(DIRECTORY_SEPARATOR, [$info['destination'], $info['name']])); $newFileName = $this->cleanFileName($uploadedFileObject->getFilename()); $fileObject = new SplFileInfo(implode(DIRECTORY_SEPARATOR, [$uploadedFileObject->getPath(), $newFileName])); $type = null; if ($adapter->receive($originalFileName)) { rename($uploadedFileObject->getPathname(), implode(DIRECTORY_SEPARATOR, [$uploadedFileObject->getPath(), $newFileName])); if (preg_match('/^image\\/jpe?g|png|gif$/', $info['type'])) { $type = 'image'; $generator = new ImageGenerator($fileObject, $fileDirectory); } else { $type = 'file'; $generator = new FileGenerator($fileObject, $fileDirectory); } $actionResponse = $generator->execute(); $actionResponse->setRenderer($renderer); $result['media'][] = ['code' => 200, 'message' => 'Success', 'file' => $actionResponse, 'type' => $type]; } else { $errorArray = $adapter->getErrors(); $result['media'][] = ['code' => 501, 'message' => array_pop($errorArray), 'file' => null, 'type' => $type]; } } return new JsonModel($result); }
public function moveFile($file) { $adapter = new Http(); $adapter->setDestination(dirname(__DIR__) . './../../../../public/useruploads/files'); $bool = $adapter->receive($file['name']); return $bool; }
public function addAction() { if (!$this->zfcUserAuthentication()->hasIdentity()) { return $this->redirect()->toRoute('zfcuser'); } $form = new UploadForm(); $optionSubject = $this->getSubjectTable()->getSubjectsForSelect(); $form->get('subject')->setAttribute('options', $optionSubject); $optionCategory = $this->getCategoryTable()->getCategoriesForSelect(); $form->get('category')->setAttribute('options', $optionCategory); $request = $this->getRequest(); if ($request->isPost()) { $file = new File(); $data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray()); $form->setData($data); $uploadPath = $this->getOptions()->getUploadFolderPath(); // Validatoren $size = new Size(array('max' => $this->getOptions()->getMaxFileSizeInByte())); $extension = new Extension($this->getOptions()->getAllowedFileExtensions()); // Filter für Zufallsnamen if ($this->options->getRandomizeFileName()) { $rename = new Rename(array('target' => $uploadPath . '/file', 'randomize' => true)); } else { $rename = null; } //TODO Add to factory $adapter = new Http(); $adapter->setValidators(array($size, $extension)); $adapter->setFilters(array($rename)); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); array_merge($dataError, $adapter->getErrors()); foreach ($dataError as $key => $row) { echo $row; } header('HTTP/1.1 500 Internal Server Error'); exit; } else { $adapter->setDestination($uploadPath); if ($adapter->receive()) { $subjectID = $data['subject']; $categoryID = $data['category']; $dbdata = array(); $dbdata['fileName'] = $data['file']['name']; $filename = $adapter->getFileName(); if (is_array($filename)) { $dbdata['url'] = basename(current($filename)); } else { $dbdata['url'] = basename($filename); } $file->exchangeArray($dbdata); $this->getFileTable()->saveFile($file, $subjectID, $categoryID); header('HTTP/1.1 200 OK'); exit; } } } return array('form' => $form); }
public function uploadAction() { $id_slab = (int) $this->getEvent()->getRouteMatch()->getParam('id_slab'); $aReturn = array(); $aDataInsert = array(); $sDestination = ROOT_DIR . '/upload/slab/' . $id_slab . '/'; (int) ($id_user = $this->getAuthService()->getStorage()->read()->id); $aDataInsert['id_slab'] = $id_slab; $aDataInsert['cr_date'] = new \Zend\Db\Sql\Expression("getdate()"); $aDataInsert['cr_user'] = $id_user; if (!is_dir($sDestination)) { if (!@mkdir($sDestination, 0777, true)) { throw new \Exception("Unable to create destination: " . $sDestination); } } $size = new Size(array('min' => 10, "max" => 10000000)); //minimum bytes filesize $count = new Count(array("min" => 0, "max" => 1)); $extension = new Extension(array("extension" => array("jpg", "png", "swf"))); $adapter = new \Zend\File\Transfer\Adapter\Http(); $file = $adapter->getFileInfo(); $adapter->setValidators(array($size, $count, $extension), $file['file']['name']); $adapter->setDestination($sDestination); if ($adapter->isValid()) { if ($adapter->isUploaded()) { if ($adapter->receive()) { $file = $adapter->getFileInfo(); $aDataInsert['photo'] = $file['file']['name']; $aDataInsert['name'] = $file['file']['name']; $this->getContainerDrawingTable()->save($aDataInsert); $aReturn['state'] = true; } } else { $aReturn['state'] = false; } } else { $dataError = $adapter->getMessages(); $error = array(); foreach ($dataError as $key => $row) { $error[] = $row; } $aReturn['state'] = false; } return new JsonModel($aReturn); }
public function importAction() { $request = $this->getRequest(); $this->form->get('type')->setValue($this->params('type')); if ($request->isPost()) { $nonFile = $request->getPost()->toArray(); $file = $this->params()->fromFiles('fileupload'); $data = array_merge($nonFile, ['fileupload' => $file['name']]); //set data post and file ... $this->form->setData($data); if ($this->form->isValid()) { //$size = new Size(array('max' => '204800B')); //minimum bytes filesize $adapter = new Http(); //$adapter->setValidators(array($size), $file['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); $error = array(); foreach ($dataError as $key => $row) { $error[] = $row; } $this->form->setMessages(['fileupload' => $error]); } else { $pathUploadFiles = $this->importer->getDriverFactory()->getConfig()['file_upload_path']; if (!is_dir($pathUploadFiles)) { mkdir($pathUploadFiles, 0775, true); } $adapter->setDestination($pathUploadFiles); //\Zend\Debug\Debug::dump([$adapter->getFileName($file['name'])]); die(__METHOD__); /*\Zend\Debug\Debug::dump([ $file['name'], $adapter->receive($adapter->getFileName('fileupload', false)), $adapter->isFiltered($file['name']), $adapter->getMessages() ]); die(__METHOD__.__LINE__);*/ //$fileName = $adapter->getFileName('fileupload', false); if ($adapter->receive($adapter->getFileName('fileupload', false))) { $this->importer->import($this->params('type'), $adapter->getFileName('fileupload')); $this->prepareMessages(); } } } } //\Zend\Debug\Debug::dump([$form->getName(), get_class($form)]); die(__METHOD__); return ['form' => $this->form]; }
public function uploadImage($fileData) { $upload = new Http(); $upload->setDestination(self::UPLOAD_PATH); try { // upload received file(s) $upload->receive(); } catch (\Exception $e) { // return $uploadResult; } //This method will return the real file name of a transferred file. $name = $upload->getFileName($fileData['upload']['name']); //This method will return extension of the transferred file $extention = pathinfo($name, PATHINFO_EXTENSION); //get random new name $newName = $this->random->getRandomUniqueName(); $newFullName = self::UPLOAD_PATH . $newName . '.' . $extention; // rename rename($name, $newFullName); $uploadResult = $newFullName; return $uploadResult; }
public function execute() { $file = new Http(); $fileInfo = $file->getFileInfo(); // armazena os caminhos dos arquivos que fizeram upload para remover em caso de erros $tempDirUpload = array(); // retorno com o nome do arquivo enviados $return = array(); foreach ($fileInfo as $id => $item) { // se for um array renomeia separadamente os arquivos if (is_array($this->rename)) { if (array_key_exists($id, $this->rename)) { $newName = $this->rename[$id] . "." . substr(strrchr($item['name'], '.'), 1); $file->setFilters(array('Rename' => $newName), $id); } } elseif ($this->rename) { $newName = md5(microtime()) . "." . substr(strrchr($item['name'], '.'), 1); $file->setFilters(array('Rename' => $newName)); // se for null fica a imagem com o nome normal } else { $newName = $item['name']; } // destino do arquivo $destination = is_array($this->destination) ? $this->path . $this->destination[$id] : $this->path . $this->destination; if (!is_dir($destination)) { mkdir($destination); } chmod($destination, "0775"); $file->setDestination($destination, $id); // validações $arrValidators = array(); // verifica se tem validação de tamanho se tiver aplica if ($this->sizeValidation !== null) { $size = isset($this->sizeValidation[$id]) ? $this->sizeValidation[$id] : $this->sizeValidation; $sizeValidation = new Size(array('min' => $size[0], 'max' => $size[1])); $arrValidators[] = $sizeValidation; } // verifica se tem validação de extensão se tiver aplica if ($this->extValidation !== null) { $ext = isset($this->extValidation[$id]) ? $this->extValidation[$id] : $this->extValidation; $extValidation = new Extension($ext); $arrValidators[] = $extValidation; } // setando as validações caso existam if (count($arrValidators)) { $file->setValidators($arrValidators, $id); } // valida o arquivo if ($file->isValid($id)) { // envia o arquivo if ($file->receive($id)) { // seta o destino do arquivo $tempDirUpload[] = $destination . "/" . $newName; // seta o nome do arquivo $return['files'][$id] = $newName; // verifica se tem destino thumb se tiver gera a thumb if (count($this->thumbOpt)) { // setando os opções obrigatórias $arrThumbOptRequire = array('destination' => 'destination', 'width' => 'width', 'height' => 'height', 'cropimage' => 'cropimage'); // Validando se todos os parâmetros foram passados foreach ($this->thumbOpt as $thumbIndex => $thumbValue) { unset($arrThumbOptRequire[$thumbIndex]); } if (count($arrThumbOptRequire)) { throw new \Exception('Configure corretamente o setThumb("destination", "width", "height", "cropimage")'); } /* * Criando a thumb usando o modulo JVEasyPhpThumbnail */ $destinationThumb = $this->path . $this->thumbOpt['destination'] . "/"; if (!is_dir($destinationThumb)) { mkdir($destinationThumb); } chmod($destinationThumb, "0775"); $phpThumb = new PHPThumb(); $phpThumb->Thumblocation = $destinationThumb; $phpThumb->Chmodlevel = '0755'; $phpThumb->Thumbsaveas = substr(strrchr($item['name'], '.'), 1); $phpThumb->Thumbwidth = $this->thumbOpt['width']; $phpThumb->Thumbheight = $this->thumbOpt['height']; $phpThumb->Cropimage = $this->thumbOpt['cropimage']; $destination = $destination . "/" . $newName; $phpThumb->Createthumb($destination, 'file'); } } } else { $keyError = $file->getErrors(); // verifica se fez algum upload se tiver exclui os arquivos, mas caso o required esteja setado como true if (count($tempDirUpload) && ($this->required && in_array('fileUploadErrorNoFile', $keyError)) || !in_array('fileUploadErrorNoFile', $keyError)) { foreach ($tempDirUpload as $filename) { unlink($filename); } } if ($this->required && in_array('fileUploadErrorNoFile', $keyError) || !in_array('fileUploadErrorNoFile', $keyError)) { return array('error' => array($id => $file->getMessages())); } } } return $return; }
/** * image upload */ public function uploadAction() { if ($this->getRequest()->isPost()) { if (!is_dir($this->path . $this->locador->getId())) { mkdir($this->path . $this->locador->getId()); } $fileTransfer = new FileTransfer(); $arquivo = $fileTransfer->getFileInfo('fachada'); //unlink($this->path.$this->locador->getId().'/original.' . strtolower(substr($arquivo['fachada']['name'], -3, 3))); $fileTransfer->setDestination($this->path . $this->locador->getId()); $fileTransfer->addFilter('Rename', array('target' => 'original.' . strtolower(substr($arquivo['fachada']['name'], -3, 3)), 'overwrite' => true)); $fileTransfer->receive(); $this->redirect()->toRoute('Locador/imovel/novo', array('etapa' => 3)); } }
protected function validateImportFile($file) { $size = new Size(array('min' => 1024, 'max' => 2048000)); // min/max bytes filesize $adapter = new FileHttp(); $ext = new FileExt(array('extension' => array('csv'))); $adapter->setValidators(array($size, $ext), $file['name']); $isValid = $adapter->isValid(); if (!$isValid) { $dataError = $adapter->getMessages(); $this->errorResponse->addMessage($dataError, "error"); } else { $adapter->setDestination($this->getUploadPath()); if ($adapter->receive($file['name'])) { $isValid = $file['name']; } } return $isValid; }
private function uploadAttachment($filename, $attachmentPath) { $uploadResult = null; $upload = new Http(); $upload->setDestination($attachmentPath); try { // upload received file(s) $upload->receive($filename); } catch (\Exception $e) { return $uploadResult; } //This method will return the real file name of a transferred file. $name = $upload->getFileName($filename); //This method will return extension of the transferred file $extention = pathinfo($name, PATHINFO_EXTENSION); //get random new name $newName = $this->random->getRandomUniqueName() . '_' . date('Y.m.d_h:i:sa'); $newFullName = $attachmentPath . $newName . '.' . $extention; // rename rename($name, $newFullName); $uploadResult = $newFullName; return $uploadResult; }
public function editarAction() { $id = $this->params('id'); $filme = $this->getFilmesTable()->getFilmes($id); $form = new FilmesForm(); $form->setBindOnValidate(false); $form->get('submit')->setLabel('Alterar'); $categories = $this->getCategoryTable()->getAllFormArray(); $form->get('categoria_id')->setValueOptions($categories); $form->bind($filme); $request = $this->getRequest(); if ($request->isPost()) { $nonFile = $request->getPost()->toArray(); $File = $this->params()->fromFiles('filmes_foto'); if ($File['name'] == "") { $name_file = $filme->filmes_foto; } else { $name_file = $File['name']; } $data = array_merge($nonFile, array('filmes_foto' => $name_file)); $form->setData($data); if ($form->isValid()) { $form->bindValues(); if ($File['name'] != "") { $size = new Size(array('max' => 2000000)); $adapter = new Http(); $adapter->setValidators(array($size), $File['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); $erro = array(); foreach ($dataError as $row) { $erro[] = $row; } $form->setMessages(array('filmes_foto' => $erro)); } else { $diretorio = $request->getServer()->DOCUMENT_ROOT . '/conteudo/filmes'; $adapter->setDestination($diretorio); if ($adapter->receive($File['name'])) { $this->flashMessenger()->addMessage(array('success' => 'A foto foi enviada com sucesso!')); } else { $this->flashMessenger()->addMessage(array('danger' => 'A foto não foi enviada!')); } } } $this->getFilmesTable()->saveFilmes($filme); $this->flashMessenger()->addMessage(array('success' => 'Registro alterado com sucesso!')); $this->redirect()->toUrl("/filmes"); } } $view = new ViewModel(array('form' => $form)); $view->setTemplate('application/filmes/form.phtml'); return $view; }
protected function validateImportFile($file) { $size = new Size(array('min' => 128, 'max' => 20480000)); // min/max bytes filesize $ext = new FileExt(array('extension' => array('xls', 'xlsx', 'csv'))); $mime = new MimeType(array('application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'text/plain', 'text/csv')); $adapter = new FileHttp(); $adapter->setValidators(array($size, $ext, $mime), $file['name']); $isValid = $adapter->isValid(); if (!$isValid) { $dataError = $adapter->getMessages(); $this->flashMessenger()->addErrorMessage($this->errorImportTypeMessage . '<br>' . implode(' <br>', $dataError)); } else { $adapter->setDestination($this->getUploadPath()); if ($adapter->receive()) { $isValid = $adapter->getFileName(null, false); } else { $dataError = $adapter->getMessages(); $this->flashMessenger()->addErrorMessage($this->errorImportTypeMessage . '<br>' . implode(' <br>', $dataError)); $isValid = false; } } return $isValid; }
/** * Upload all images async. * * @return JsonModel */ public function prepareImages() { $adapter = new Http(); $size = new Size(['min' => '10kB', 'max' => '5MB', 'useByteString' => true]); $extension = new Extension(['jpg', 'gif', 'png', 'jpeg', 'bmp', 'webp', 'svg'], true); $adapter->setValidators([$size, new IsImage(), $extension]); $this->makeDir('public/'); $adapter->setDestination('public/userfiles/' . date('Y_M') . '/images/'); $data = $this->uploadFiles($adapter); return new JsonModel($data); }
public function addAction() { if ($this->getLoginTable()->validarSessao()) { $this->redirect()->toRoute('login'); } $adapter = new Http(); $destino = dirname(dirname(dirname(dirname(dirname(__DIR__))))) . '/public/img/fotos/'; $adapter->setDestination($destino); $request = $this->getRequest(); $titulo = $id_update = $pasta = $hidden = $saida = null; if ($request->isPost()) { $titulo = $request->getPost('titulo'); $titulo = str_replace("/", "-", $titulo); $id_update = $request->getPost('id'); date_default_timezone_set('America/Sao_Paulo'); $pasta = date("dmYHis"); $files = $adapter->getFileInfo(); if (!empty($files)) { mkdir($destino . $pasta . '/', 0777); $qtd = 0; foreach ($files as $file => $info) { //$adapter->addFilter('Rename', $destino . $pasta . '/' . $info['name']); $adapter->addFilter('Rename', $destino . $pasta . '/' . $qtd . '.jpg'); $adapter->receive($file); $this->lista[$qtd] = '/nortes/public/img/fotos/' . $pasta . '/' . $qtd . '.jpg'; $qtd++; } $saida = $this->getPortfolioTable()->printFormulario($this->lista, $titulo, $pasta, null, null); $hidden = 'hidden = "true" '; } else { if (!is_null($id_update)) { $fotos_update = $this->getFotosTable()->changeFotos($id_update); $qtd = 0; $id_fotos = array(); foreach ($fotos_update as $ft) { $this->lista[$qtd] = '/nortes/public/img/fotos/' . $id_update . '/' . $ft['id'] . '.jpg'; $id_fotos[$qtd] = $ft; $qtd++; } $hidden = 'hidden = "true" '; $saida = $this->getPortfolioTable()->printFormulario($this->lista, $titulo, null, $id_update, $id_fotos); } } return array('titulo' => $titulo, 'saida' => $saida, 'hidden' => $hidden); } }
public function editAction() { try { $id = $this->params('id', false); $em = $this->getEntityManager(); if ($id) { $form = new RecruitmentForm($em); $recruitment = $em->find('Recruitment\\Entity\\Recruitment', $id); $currentDate = new \DateTime(); $beginDate = \DateTime::createFromFormat('d/m/Y', $recruitment->getRecruitmentBeginDate()); if ($beginDate <= $currentDate) { return new ViewModel(array('message' => 'Não é possível editar processos seletivos concluídos ou em andamento. Por favor, consulte o administrador do sistema.', 'form' => null)); } $form->bind($recruitment); $request = $this->getRequest(); if ($request->isPost()) { $publicNotice = $recruitment->getRecruitmentPublicNotice(); $fileContainer = $request->getFiles()->toArray(); $file = $fileContainer['recruitment']['recruitmentPublicNotice']; $data = $request->getPost(); $form->setData($data); if ($form->isValid() && !$file['error'] && $file['size']) { try { $filename = $data['recruitment']['recruitmentYear'] . $data['recruitment']['recruitmentNumber'] . $data['recruitment']['recruitmentType'] . '.pdf'; $recruitment->setRecruitmentPublicNotice($filename); $em->persist($recruitment); $em->flush(); $targetDir = self::PUBLIC_NOTICE_DIR; $targetFile = $targetDir . $filename; if (file_exists($targetFile)) { unlink(self::PUBLIC_NOTICE_DIR . $publicNotice); } $uploadAdapter = new HttpAdapter(); $uploadAdapter->addFilter('File\\Rename', array('target' => $targetFile, 'overwrite' => true)); $uploadAdapter->setDestination($targetDir); if (!$uploadAdapter->receive($fileContainer['name'])) { $messages = implode('\\n', $uploadAdapter->getMessages()); throw new \RuntimeException($messages); } return $this->redirect()->toRoute('recruitment/recruitment', array('action' => 'index')); } catch (\Thrownable $ex) { if ($ex instanceof UniqueConstraintViolationException) { return new ViewModel(array('message' => 'Este processo seletivo já foi cadastrado.', 'form' => null)); } return new ViewModel(array('message' => 'Erro inesperado: ' . $ex->getMessage(), 'form' => null)); } } return new ViewModel(array('message' => $file['error'] || !$file['size'] ? 'O upload do edital não pode ser feito. Por favor tente novamente.' : null, 'form' => $form)); } return new ViewModel(array('form' => $form, 'message' => null)); } return new ViewModel(array('form' => null, 'message' => 'Nenhum Processo Seletivo foi escolhido')); } catch (\Exception $ex) { return new ViewModel(array('form' => null, 'message' => $ex->getMessage())); } }
/** * Upload all images async. * * @return array */ private function prepareImages() { $adapter = new Http(); $size = new Size(['min' => '10kB', 'max' => '5MB', 'useByteString' => true]); $extension = new Extension(['jpg', 'gif', 'png', 'jpeg', 'bmp', 'webp', 'svg'], true); if (extension_loaded('fileinfo')) { $adapter->setValidators([new IsImage()]); } $adapter->setValidators([$size, $extension]); $adapter->setDestination('public/userfiles/images/'); return $this->uploadFiles($adapter); }