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 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 postAction() { $request = $this->getRequest(); if ($request->isPost()) { $product = new Product(); $product->name = $request->getPost('name'); $product->price = $request->getPost('price'); $product->manufacture = $request->getPost('manufacture'); $product->inventory_number = $request->getPost('inventory_number'); $product->date = $request->getPost('date'); $product->show = $request->getPost('show'); // Get images $temp = array(); $imgTotal = intval($request->getPost('imgTotal')); $httpadapter = new Http(); $httpadapter->addValidator('Size', true, array('min' => 1000)); $httpadapter->addValidator('Extension', true, array('png', 'jpg', 'jpeg')); for ($i = 0; $i < $imgTotal; $i++) { $fileName = 'image_' . $i; $image = $request->getFiles($fileName); $httpadapter->addFilter('Rename', array('target' => __UPLOAD__ . '/products/' . $product->name . '-' . $image['name'], 'randomize' => true)); if ($httpadapter->isValid()) { if ($httpadapter->receive($image['name'])) { $temp[] = $httpadapter->getFileInfo()[$fileName]['name']; } } } $product->images = implode(';', $temp); $product->display = $request->getPost('display'); $product->os = $request->getPost('os'); $product->cpu = $request->getPost('cpu'); $product->camera = $request->getPost('camera'); $product->internal_memory = $request->getPost('internal_memory'); $product->ram = $request->getPost('ram'); $product->battery = $request->getPost('battery'); $product->more = $request->getPost('more'); // Insert product if ($this->getProductTable()->insertProduct($product)) { echo json_encode('successful'); } else { echo json_encode('Insert error'); } exit; } }
public function updateAction() { $id = $this->params()->fromRoute('id'); $request = $this->getRequest(); $message = null; if ($request->isPost()) { // Get file upload $files = $request->getFiles()->toArray(); $filePostName = 'image'; $file = $files[$filePostName]; // Check validate $httpadapter = new Http(); $httpadapter->addValidator('Size', true, array('min' => 1000), $filePostName); $httpadapter->addValidator('Extension', true, array('png', 'jpg', 'jpeg'), $filePostName); // Rename file upload $httpadapter->addFilter('Rename', array('target' => __UPLOAD__ . '/ads/' . $file['name'], 'randomize' => true), $filePostName); // Save file upload $newFileName = null; if ($httpadapter->isValid()) { if ($httpadapter->receive($file['name'])) { $fileInfo = $httpadapter->getFileInfo(); $newFileName = $fileInfo[$filePostName]['name']; } } $adsPost = new Advertise(); $adsPost->id = $id; $adsPost->image = $newFileName; $adsPost->link = $request->getPost('link'); $adsPost->date_start = $request->getPost('date_start'); $adsPost->date_end = $request->getPost('date_end'); $adsPost->location = $request->getPost('location'); $adsPost->show = $request->getPost('show'); $adsPost->view_count = $request->getPost('view_count'); $adsPost->click_count = $request->getPost('click_count'); $result = $this->getAdvertiseTable()->updateAdvertise($adsPost); if ($result) { $message = 'Successful!'; } else { $message = 'Error!! Please try again.'; } } $ads = $this->getAdvertiseTable()->getAdvertiseById($id); return new ViewModel(array('ads' => $ads, 'message' => $message)); }
public function updateAction() { $request = $this->getRequest(); if ($request->isPost()) { // Get file upload $files = $request->getFiles()->toArray(); $logo = $files['logo']; // Check validate $httpadapter = new Http(); $httpadapter->addValidator('Size', true, array('min' => 1000)); $httpadapter->addValidator('Extension', true, array('png', 'jpg', 'jpeg')); // Rename file upload $httpadapter->addFilter('Rename', array('target' => __UPLOAD__ . '/page/' . $logo['name'], 'randomize' => true)); // Save file upload $newFileName = null; if ($httpadapter->isValid()) { if ($httpadapter->receive($logo['name'])) { $fileInfo = $httpadapter->getFileInfo(); $newFileName = $fileInfo['logo']['name']; } } $data = new Info(); $data->name = $request->getPost('name'); if (isset($newFileName)) { $data->logo = '/upload/page/' . $newFileName; } else { $data->logo = null; } $data->address = $request->getPost('address'); $data->tel = $request->getPost('tel'); $data->introduce = $request->getPost('introduce'); $data->image = $request->getPost('image'); $this->getInfoTable()->updateInfo($data); } $this->redirect()->toRoute('shopinfo'); }
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)); } }
/** * @param Http $adapter * * @return array */ private function uploadFiles(Http $adapter) { $uploadStatus = []; foreach ($adapter->getFileInfo() as $key => $file) { if (!$adapter->isValid($file['name'])) { foreach ($adapter->getMessages() as $key => $msg) { $uploadStatus['errorFiles'][] = $file['name'] . ' ' . strtolower($msg); } } // @codeCoverageIgnoreStart if (!$adapter->receive($file['name'])) { $uploadStatus['errorFiles'][] = $file['name'] . ' was not uploaded'; } else { $uploadStatus['successFiles'][] = $file['name'] . ' was successfully uploaded'; } // @codeCoverageIgnoreEnd } return $uploadStatus; }
/** * @param Http $adapter * * @return array */ private function uploadFiles(Http $adapter) { $uploadStatus = []; foreach ($adapter->getFileInfo() as $key => $file) { if ($key !== 'preview') { // @codeCoverageIgnoreStart $arr1 = $this->validateUploadedFileName($adapter, $file['name']); $arr2 = $this->validateUploadedFile($adapter, $file['name']); $uploadStatus = array_merge_recursive($arr1, $arr2); // @codeCoverageIgnoreEnd } } return $uploadStatus; }
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); } }
/** * @param int $userId - used to create a folder for the current user and rename the image * * @return void */ private function uploadImage($userId = 0) { $userId = (int) $userId; $messages = []; $dir = 'public/userfiles/images/user-' . $userId . '/'; $adapter = new Http(); $size = new Size(['min' => '10kB', 'max' => '5MB', 'useByteString' => true]); $extension = new Extension(['jpg', 'gif', 'png', 'jpeg', 'bmp', 'webp', 'svg'], true); if (!is_dir($dir)) { mkdir($dir, 0750, true); } foreach ($adapter->getFileInfo() as $file) { $ext = pathinfo($file['name'], PATHINFO_EXTENSION); $newName = $userId . '.' . $ext; $adapter->setValidators([$size, new IsImage(), $extension]); $adapter->addFilter('File\\Rename', ['target' => $dir . $newName, 'overwrite' => true]); $adapter->receive($file['name']); if (!$adapter->isReceived($file['name']) && $adapter->isUploaded($file['name'])) { $messages[] = $file['name'] . ' was not uploaded'; } } $this->setLayoutMessages($messages, 'info'); }