public function uploadAction() { $request = $this->getRequest(); if (!$request->isPost()) { return; } $name = $this->_getParam('name', false); $upload = new Zend_File_Transfer(); $upload->addValidator('Count', false, 1); if (!$upload->isValid()) { return; } $upload->receive(); $file = $upload->getFileName(); $fp = fopen($file, "r"); if (!$fp) { return; } $mime = $upload->getMimeType(); if (!$name) { // get short name $name = $upload->getFileName(null, false); } $this->_storage->storeItem($name, $fp, array(Zend_Cloud_StorageService_Adapter_S3::METADATA => array("type" => $mime))); try { $this->_storage->storeMetadata($name, array("type" => $mime)); } catch (Zend_Cloud_OperationNotAvailableException $e) { // ignore it } return $this->_helper->redirector('index'); }
/** * Sube el archivo a temporal * @return string */ public function upload($extenciones = array('kml', 'kmz')) { $correcto = true; $upload = new Zend_File_Transfer(); $upload->addValidator('Extension', false, $extenciones); $upload->addValidator('FilesSize', false, array('min' => '0.001kB', 'max' => '64MB')); $file = $upload->getFileInfo(); foreach ($file as $field_name => $file_data) { if (!$upload->isUploaded($field_name)) { $correcto = false; $retorno = array("correcto" => false, "mensaje" => "No se subio ningún archivo o estaba vacío"); } if (!$upload->isValid($field_name)) { $texto = "</br>"; $mensajes = $upload->getMessages(); foreach ($mensajes as $key => $txt) { $texto .= $txt . "</br>"; } $correcto = false; $retorno = array("correcto" => false, "mensaje" => "<b>El archivo es inválido</b>." . $texto); } $this->_setFileConfig($file_data["name"]); $this->_mime = $file_data["type"]; $this->_hash = $this->_ci->string_core->rand_string(20); $this->_target = $this->_dir_temp . $this->_hash . "." . $this->_file_ext; $upload->addFilter('Rename', array('target' => $this->_target, 'overwrite' => true)); } if ($correcto) { fb($upload->receive()); $retorno = $this->_saveToCache(); } return $retorno; }
public function direct($exts = array('xml', 'csv', 'txt')) { $front = Zend_Controller_Front::getInstance(); $front->registerPlugin(new \Tid_Zend_Controller_Plugin_UploadMax()); // Frontend HACK if ($this->getRequest()->getParam('iframeHack', false)) { $h = Zend_Controller_Action_HelperBroker::getStaticHelper('Output'); $h->direct('json')->setContentType('text/html'); } // Preprocess mime types $mimes = array(); foreach ($exts as $ext) { if (!isset($this->_mimeTypes[$ext])) { throw new \Application\Exceptions\InvalidArgumentException("Unsupported extension {$ext}"); } if (!in_array($this->_mimeTypes[$ext], $mimes)) { $mimes[] = $this->_mimeTypes[$ext]; } } // Upload file $upload = new Zend_File_Transfer(); $mimes['headerCheck'] = true; $upload->addValidator('Count', true, array('min' => 1, 'max' => 1))->addValidator('Extension', true, $exts)->addValidator('MimeType', true, $mimes)->addValidator('Size', true, array('max' => '20MB')); // Validate file if (!$upload->isValid()) { throw new \Application\Exceptions\ValidateException('Invalid file', array('validationErrors' => $upload->getMessages(), 'entity' => 'file', 'code' => ValidationCodes::FILE_UPLOAD_ERR)); } if (!$upload->receive()) { throw new \Application\Exceptions\InvalidArgumentException('Could not receive file', ValidationCodes::FILE_UPLOAD_ERR); } return $upload; }
/** * 上传用户文件的action */ public function uploadUserDocAction() { $this->_helper->layout->disableLayout(); $doctype = $this->request->getParam('doctype'); $this->view->doctype = $doctype; $result = 0; if ($this->request->isPost()) { $upload = new Zend_File_Transfer(); $upload->addValidator('Size', false, 10240000); //10M $utilService = $this->_container->get('util'); $fileService = $this->_container->get('file'); $filename = $utilService->getFilename($upload->getFileName()); $extension = $fileService->getExtensionByFilename($filename); $destination = $utilService->getTmpDirectory() . DIRECTORY_SEPARATOR . uniqid(); $upload->addFilter('Rename', $destination); if ($upload->isValid()) { if ($upload->receive()) { $userModel = $this->getModel('user'); $mimetype = $upload->getMimeType(); if ($fileService->isAcceptedDocument($mimetype, $extension)) { $user = $userModel->getUserById($this->me->getId()); if ($user) { $doc = null; if ($doctype == \Angel_Model_User::FILETYPE_IDENTITY_FRONT || $doctype == \Angel_Model_User::FILETYPE_IDENTITY_BACK) { $doc = $userModel->addUserDoc($user, $doctype, $destination, $filename, $mimetype); } if ($doc) { $result = 1; $this->view->filename = $doc->filename; $this->view->path = $this->view->url(array('doctype' => $doctype, 'user_id' => $user->id, 'doc_id' => $doc->id), 'user-doc'); } } } else { // 上传的文件格式不接受 $result = 2; } } } } $this->view->result = $result; }
public function importSeasons() { $option = JRequest::getCmd('option'); $controller = JRequest::getCmd('controller'); // Check for request forgeries JRequest::checkToken() or die('Invalid Token'); $path = JPATH_ROOT . "/tmp"; $upload = new Zend_File_Transfer(); $upload->setDestination($path); $upload->addValidator('Extension', false, array("csv")); $errors = array(); $file = "products_seasons"; $info = $upload->getFileInfo($file); if ($upload->isUploaded($file)) { if (!$upload->isValid($file)) { foreach ($upload->getMessages() as $k => $v) { $errors[$k] = true; } } } if ($upload->receive()) { $mProduct = new EcwidgatewayModelProducts(); $mProduct->processSeasonsCsv($path . "/" . $info[$file]["name"]); $msg = "Данные импортированы"; } else { $errorMessages = array("Ошибка при загрузке файла"); foreach ($errors as $k => $v) { if (isset($errors[Zend_Validate_File_Extension::FALSE_EXTENSION])) { $errorMessages[] = JText::_("Недопустимое расширение файла"); } } $msg = implode("<p>", $errorMessages); } $link = 'index.php?option=' . $option . '&controller=' . $controller; $this->setRedirect($link, $msg); }
public function applyAction() { $this->view->pageTitle = 'Careers'; if ($this->getRequest()->isPost()) { // Handle the cv file and form data $filters = array('name' => 'StringTrim', 'tel' => 'StringTrim', 'email' => 'StringTrim', 'enquiry' => 'StringTrim'); $validators = array('name' => array('NotEmpty', 'messages' => 'Please enter your name'), 'tel' => array('NotEmpty', 'messages' => 'Please enter your telephone number'), 'email' => array('NotEmpty', 'messages' => 'Please enter your email address'), 'enquiry' => array('NotEmpty', 'messages' => 'Please tell us why this position interests you')); $input = new Zend_Filter_Input($filters, $validators, $_POST); if ($input->isValid()) { $upload = new Zend_File_Transfer(); // Make sure the file is actually a document $upload->clearValidators(); $upload->setOptions(array('ignoreNoFile' => true)); //$upload->addValidator('MimeType', false, array('application/msword', 'application/pdf', 'application/rtf', 'text/plain')); if ($upload->isValid()) { $params = Zend_Registry::get('params'); $uploadPath = $params->cms->fileUploadPath; $upload->setDestination($uploadPath); $upload->receive(); $fileInfo = $upload->getFileInfo(); $emailer = new Application_Core_Mail(); $emailer->setTo($params->email->careers, 'HomeLet'); $emailer->setFrom($input->email, $input->name); $emailer->setSubject('HomeLet - Job Application (' . $input->position . ')'); $bodyHtml = 'Position : ' . $input->position . '<br />'; $bodyHtml .= 'Name : ' . $input->name . '<br />'; $bodyHtml .= 'Email : ' . $input->email . '<br />'; $bodyHtml .= 'Tel : ' . $input->tel . '<br />'; $bodyHtml .= 'Enquiry : <pre>' . $input->enquiry . '</pre><br />'; if ($fileInfo['cv_file']['type'] !== null) { $emailer->addAttachment($fileInfo['cv_file']['destination'] . '/' . $fileInfo['cv_file']['name'], $fileInfo['cv_file']['name']); } $emailer->setBodyHtml($bodyHtml); if ($emailer->send()) { $this->_helper->redirector('thanks', 'careers'); } else { } } else { // Invalid file type $this->view->errors = array('cv_file' => 'Invalid file type'); $this->view->name = $input->name; $this->view->tel = $input->tel; $this->view->email = $input->email; $this->view->enquiry = $input->enquiry; } } else { // Invalid form data $this->view->errors = $input->getMessages(); $this->view->name = $input->name; $this->view->tel = $input->tel; $this->view->email = $input->email; $this->view->enquiry = $input->enquiry; } } $careerUrl = $this->getRequest()->getParam('careerID'); $careerID = substr($careerUrl, 0, strpos($careerUrl, '-')); $careers = new Datasource_Cms_Careers(); $career = $careers->getById($careerID); $this->view->title = $career['title']; $this->view->id = $career['id']; }
public function saveAction() { $request = $this->getRequest(); $id = $this->getParam('id'); $auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { $user_id = $auth->getIdentity()->id; } $form = $this->getSaveProductForm($id); if ($this->getRequest()->isPost()) { if ($form->isValid($request->getPost())) { $data = $this->getRequest()->getParams(); $upload = new Zend_File_Transfer(); $files = $upload->getFileInfo(); $isValid = true; foreach ($files as $field => $file) { if (!strlen($file["name"])) { continue; } $extension = pathinfo($file['name'], PATHINFO_EXTENSION); $filename = pathinfo($file['name'], PATHINFO_FILENAME); if (!file_exists(UPLOADS_IMAGES)) { mkdir(UPLOADS_IMAGES, 0774, true); } if (!file_exists(UPLOADS_DATA)) { mkdir(UPLOADS_DATA, 0774, true); } // upload instructions for image if ($field == 'image') { $upload->addFilter('Rename', array('target' => UPLOADS_IMAGES . '/' . $filename . "_" . $user_id . "_" . time() . "." . $extension, 'overwrite' => TRUE), $field)->addValidator('Extension', false, array('jpg', 'jpeg', 'png'), $field); $data['image'] = $filename . "_" . $user_id . "_" . time() . "." . $extension; } // upload instructions for file if ($field == 'file') { $upload->addFilter('Rename', array('target' => UPLOADS_DATA . '/' . $filename . "_" . $user_id . "_" . time() . "." . $extension, 'overwrite' => TRUE), $field)->addValidator('Extension', false, array('doc', 'docx', 'txt', 'pdf'), $field); $data['file'] = $filename . "_" . $user_id . "_" . time() . "." . $extension; } if ($upload->isValid($field)) { if (!$upload->receive($field)) { $isValid = false; foreach ($upload->getMessages() as $key => $val) { $this->_helper->getHelper('FlashMessenger')->addMessage($val, 'error'); } } } else { $isValid = false; $this->_helper->getHelper('FlashMessenger')->addMessage($file['name'] . " is not valid {$field}", 'error'); //return $this->_helper->redirector('save'); } } if ($upload->hasErrors()) { $errors = $upload->getMessages(); foreach ($errors as $error) { $this->_helper->getHelper('FlashMessenger')->addMessage("{$error}", 'error'); } return $this->_helper->redirector('save'); } if ($isValid) { $product = new Application_Model_Product(); $productMapper = new Application_Model_ProductMapper(); if ($id) { $product = $productMapper->getProductById($id); } if (isset($data['file']) && $product->file && $product->file != $data['file'] || !isset($data['file']) && $product->file) { $productMapper->delete_file($product->file); } if (isset($data['image']) && $product->image && $product->image != $data['image'] || !isset($data['image']) && $product->image) { $productMapper->delete_image($product->image); } $product = new Application_Model_Product($data); $productMapper->save($product); return $this->_helper->redirector('dashboard', 'users'); } } } $this->view->headScript()->appendFile(JS_DIR . '/' . self::DELETE_FIELD . '.js'); $this->view->form = $form; }
public function filesAction() { if (!$this->getRequest()->isPost()) { throw new AppEx\ForbiddenException("Files action must be a post request."); } $front = Zend_Controller_Front::getInstance(); $front->registerPlugin(new \Tid_Zend_Controller_Plugin_UploadMax()); try { $upload = new Zend_File_Transfer('App_File_Transfer_Adapter_HttpMultipartMixed', false, array('ignoreNoFile' => true)); } catch (Zend_File_Transfer_Exception $e) { throw new AppEx\InvalidArgumentException($e->getMessage()); } $upload->addValidator('Count', true, array('min' => 1, 'max' => 1))->addValidator('Extension', true, array('xml', 'csv', 'txt'))->addValidator('MimeType', true, array('application/xml', 'text/plain', 'headerCheck' => true)); if ($upload->isValid()) { if ($upload->receive()) { try { $fileinfo = current($upload->getFileInfo()); $filename = $fileinfo['tmp_name']; // Attempt to parse data from file $parseResult = $this->_stockSrv->getData($filename, $upload->getMimeType()); $data = $parseResult['data']; $errors = $parseResult['errors']; if (!empty($errors) && is_array($errors)) { foreach ($errors as $errMess) { require_once APPLICATION_PATH . '/modules/default/controllers/ErrorController.php'; $errMess->code = ErrorController::finishErrorCode($errMess->code); } } $method = 'create' . ucfirst($data['_type']); if (!empty($data['_type']) && is_callable(array($this->_stockSrv, $method))) { // Check permissions according to the data type $dumbSim = new Application\Model\SimModel(); $this->_helper->allowed($data['_perm'], $dumbSim); try { $watcher = $this->_stockSrv->{$method}($parseResult); } catch (AppEx\GlobalServiceException $ex) { $ex->addErrorMessages($errors); throw $ex; } $txId = uniqid('parser'); WatcherService::getInstance()->pushEntityId($watcher, $txId); $event = new EventModel(); $event->entityId = $txId; $event->entityType = 'transaction'; $event->namespace = 'connectivity'; $event->eventData = $errors; $event->created = time(); $event->forceFinish = true; WatcherService::getInstance()->publishEvent($event); // WatcherService::getInstance()->setStatus($watcher->id, WatcherModel::STATUS_FINISHED); $errors_ex = $this->_loadErrorsFromWatcher($watcher); if (!empty($errors_ex)) { $errors = Zend_Json::encode($errors_ex); App::log()->warn("Error on file upload in stock:\n" . $errors); throw new AppEx\StockParserException("Some errors uploading file to stock.", array('errorMessages' => $errors_ex)); } } else { throw new AppEx\UnexpectedException('Unknown data type (' . $data['_type'] . ')'); } } catch (PermissionException $e) { throw $e; } catch (StockParserException $e) { throw $e; } catch (GlobalServiceException $e) { $txId = uniqid('parser'); if (!isset($watcher)) { $watcher = $this->_stockSrv->createFileWatcher(); $watcher->entityIds = array($txId); $watcher->params->type = 'sim'; $watcher->params->action = 'stockUpload'; $watcher->save(); } else { WatcherService::getInstance()->pushEntityId($watcher, $txId); } $event = new EventModel(); $event->entityId = $txId; $event->entityType = 'transaction'; $event->namespace = 'connectivity'; $event->created = time(); $event->modified = time(); $event->pushEventData = true; $eventData = array(); $errors = $e->getErrorMessages(); $eventData['hasFailures'] = true; if (!empty($errors) && is_array($errors)) { require_once APPLICATION_PATH . '/modules/default/controllers/ErrorController.php'; foreach ($errors as $errMess) { if ($errMess instanceof ErrorModel) { $errMess->code = ErrorController::finishErrorCode($errMess->code); } } $eventData['message'] = array('failed' => $errors); } $event->eventData = $eventData; $event->forceFinish = true; $compressor = new ErrorModelCompressEvent(); $compressor->compress($event); WatcherService::getInstance()->publishEvent($event); // WatcherService::getInstance()->setStatus($watcher->id, WatcherModel::STATUS_FINISHED); $errors = $this->_loadErrorsFromWatcher($watcher); if (!empty($errors)) { App::log()->warn("Error on file upload in stock:\n" . Zend_Json::encode($errors)); throw new AppEx\StockParserException("Some errors uploading file to stock.", array('errorMessages' => $errors)); } } } else { throw new AppEx\InvalidArgumentException('Could not receive file'); } } else { throw new AppEx\InvalidArgumentException('Invalid file: ' . implode(', ', $upload->getMessages())); } }
/** * Upload a new file for this user if one is present in the form data, or if * not, check if one has been uploaded previously. If there's one known * about, return its name. Uses session to persist an uploaded file's * details between form submission attempts, in the case the overall form * doesn't validate. * * @todo Move somewhere else. * * @return array Array indicating boolean true for success plus and an * associative array with uploaded file information (or empty array if no * file), or boolean false for failure and an array of error messages. */ private function _uploadPersistentCompanyApplicationFile() { // For storing original filename intact $session = new Zend_Session_Namespace('homelet_connect_referencing'); $tempFile = "{$this->_params->connect->tempPrivatePath}companyApp_{$this->_agentSchemeNumber}_{$this->_agentId}"; // Is a new file being sent? $upload = new Zend_File_Transfer('http'); if ($upload->isUploaded()) { $upload->getValidator('Upload')->setMessages(array(Zend_Validate_File_Upload::INI_SIZE => 'The uploaded file size exceeds system maximum (' . ini_get('upload_max_filesize') . ')', Zend_Validate_File_Upload::FORM_SIZE => 'The uploaded file size exceeds the HTML form maximum', Zend_Validate_File_Upload::PARTIAL => 'The uploaded file was only partially uploaded', Zend_Validate_File_Upload::NO_FILE => 'No file was uploaded', Zend_Validate_File_Upload::NO_TMP_DIR => 'Missing a temporary folder', Zend_Validate_File_Upload::CANT_WRITE => 'Failed to write file to disk', Zend_Validate_File_Upload::EXTENSION => 'File upload stopped by extension', Zend_Validate_File_Upload::UNKNOWN => 'Unknown upload error')); $upload->addValidator('Count', true, 1); $upload->addValidator('Size', false, $this->_params->connect->companyapps->fileUpload->maxSize->file); $upload->getValidator('Size')->setMessages(array(Zend_Validate_File_Size::TOO_SMALL => 'File \'%value%\' below minimum size', Zend_Validate_File_Size::TOO_BIG => 'File \'%value%\' above maximum size')); $upload->addValidator('MimeType', false, $this->_params->connect->companyapps->fileUpload->mimeTypes); $upload->getValidator('MimeType')->setMessages(array(Zend_Validate_File_MimeType::FALSE_TYPE => 'File \'%value%\' of incorrect MIME type')); $upload->addValidator('Extension', true, $this->_params->connect->companyapps->fileUpload->extensions); $upload->getValidator('Extension')->setMessages(array(Zend_Validate_File_Extension::FALSE_EXTENSION => 'File \'%value%\' of incorrect extension')); if ($upload->isValid()) { // First delete any old file that may have been previously // uploaded $this->_deleteCompanyApplicationFile(); // Upload new one $session->companyAppFile->originalFilename = $upload->getFileName(null, false); $upload->addFilter('Rename', $tempFile); if ($upload->receive()) { $session->companyAppFile->uploadedFile = $tempFile; } else { unset($session->companyAppFile); } } else { // Send back validation messages return array(false, $upload->getMessages()); } } // Is there one stored, perhaps already? If yes, return original // filename $returnVal = array(); if (isset($session->companyAppFile->originalFilename)) { $returnVal = array('originalName' => $session->companyAppFile->originalFilename, 'pathToFile' => $tempFile); } return array(true, $returnVal); }
function regAction() { if ($this->_request->isPost('reg-form')) { Zend_Loader::loadClass('Zend_Filter_StripTags'); Zend_Loader::loadClass('Zend_File_Transfer'); Zend_Loader::loadClass('Zend_Date'); Zend_Loader::loadClass('Zend_Mail'); Zend_Loader::loadClass('Zend_Validate_EmailAddress'); Zend_Loader::loadClass('Zend_Validate_StringLength'); Zend_Loader::loadClass('Zend_Validate_Alnum'); $filter = new Zend_Filter_StripTags(); $email = trim($filter->filter($this->_request->getPost('reg-email'))); $username = trim($filter->filter($this->_request->getPost('reg-name'))); $password = trim($filter->filter($this->_request->getPost('reg-pswd'))); $password_confirm = trim($filter->filter($this->_request->getPost('reg-pswd-verification'))); $real_name = trim($filter->filter($this->_request->getPost('reg-real-name'))); $file_name = ''; $warnings = new Zend_Session_Namespace(); $warnings->username = $username; $warnings->email = $email; $warnings->real_name = $real_name; $warnings->error = ''; $error_msg = ''; $mail_val = new Zend_Validate_EmailAddress(); $name_lenght_val = new Zend_Validate_StringLength(6, 12); $name_an_val = new Zend_Validate_Alnum(); $pass_lenght_val = new Zend_Validate_StringLength(6, 16); $real_name_lenght_val = new Zend_Validate_StringLength(0, 60); if ($email == '') { $error_msg .= '<p>Enter your email.</p>'; } else { if (!$mail_val->isValid($email)) { foreach ($mail_val->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } } else { $data = new Users(); $query = 'email = "' . $email . '"'; $data_row = $data->fetchRow($query); if ($data_row['email'] != '') { $error_msg .= '<p>User with such an email is already registered.</p>'; } } } if ($username == '') { $error_msg .= '<p>Enter your username.</p>'; } else { if (!$name_lenght_val->isValid($username) || !$name_an_val->isValid($username)) { foreach ($name_lenght_val->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } foreach ($name_an_val->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } } else { $data = new Users(); $query = 'login = "******"'; $data_row = $data->fetchRow($query); if ($data_row['login'] != '') { $error_msg .= '<p>User with such an username is already registered.</p>'; } } } if ($password == '' || !$pass_lenght_val->isValid($password)) { $error_msg .= '<p>Enter password (must consist 6 to 16 characters).</p>'; } else { if ($password_confirm == '') { $error_msg .= '<p>Empty verification password.</p>'; } else { if ($password != $password_confirm) { $error_msg .= '<p>The entered passwords do not match.</p>'; } else { $salt = substr(sha1(microtime(true) . rand(1, 99999)), 0, 3); $password = sha1($password . $salt); } } } if ($real_name != '') { if (!$real_name_lenght_val->isValid($real_name)) { foreach ($real_name_lenght_val->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } } } $upload = new Zend_File_Transfer(); if ($upload->isUploaded()) { $upload->setDestination('public/upload/avatars/'); $upload->addValidator('IsImage', false); $upload->addValidator('Size', false, 1024 * 1024); if (!$upload->isValid()) { foreach ($upload->getMessages() as $message) { $error_msg .= '<p>' . $message . '</p>'; } } else { $upload_info = $upload->getFileName(); $file_ext = mb_substr($upload_info, strrpos($upload_info, '.') + 1); $file_name = $username . '.' . $file_ext; $upload->addFilter('Rename', array('target' => 'public/upload/avatars/' . $file_name, 'overwrite' => true)); } } if ($error_msg != '') { $warnings->error = $error_msg; $warnings->status = ''; $this->_redirect('/register/'); return; } else { $date = new Zend_Date(); $current_date = $date->toString('YYYY-MM-dd'); $upload->receive(); $data = array('login' => $username, 'email' => $email, 'password' => $password, 'salt' => $salt, 'real_name' => $real_name, 'reg_date' => $current_date, 'avatar' => $file_name, 'last_login' => '-'); $user = new Users(); $user->insert($data); $warnings->error = '<p>Registration complete.</p><p>Now check your E-Mail to activate your profile.</p>'; $warnings->username = ''; $warnings->email = ''; $warnings->real_name = ''; $warnings->status = ' reg_ok'; $mail = new Zend_Mail(); $hash = sha1($email . $salt); $url = $this->getRequest()->getServer('HTTP_HOST'); $mail->setBodyHtml('<p>To activate your profile follow the link below:</p> <p>Link: <a href="http://' . $url . '/register/activate/' . $hash . '">http://' . $url . '/register/activate/' . $hash . '</a></p> <p>Thanks for your registration.</p> '); $mail->setFrom('*****@*****.**', 'Administrator'); $mail->addTo($email, $username); $mail->setSubject('Test activation link'); $mail->send(); $this->_redirect('/register/'); return; } } }
public function photoUploadAction() { if ($this->request->isPost()) { // POST METHOD $result = 0; $upload = new Zend_File_Transfer(); $upload->addValidator('Size', false, 5120000); //5M $uid = uniqid(); $destination = $this->getTmpFile($uid); $upload->addFilter('Rename', $destination); if ($upload->isValid()) { if ($upload->receive()) { $result = $uid; } } echo $result; exit; } else { // GET METHOD $this->view->title = "上传图片"; } }
public function imageuploadAction() { $ArticleMapper = new Application_Model_ImageinfoMapper(); $method = $this->_request->getParam("method"); if ($method == "post") { $deptid = $this->_request->getParam("deptid"); //实例化文件上传类 $upload = new Zend_File_Transfer(); $upload->addValidator('Size', false, 5 * 1024 * 1024); $upload->addValidator('Extension', false, 'jpg,gif,png'); if (!$upload->isValid()) { echo "<script>alert('格式不符或文件过大,请重新尝试');location.href = '/admin/imageupload';</script>"; exit; } //获取上传的文件表单,可以有多项 $fileInfo = $upload->getFileInfo(); $parseImg = new Application_Model_Admin_Admin(); $filetmp = $parseImg->resize_image($fileInfo['imageFile']['name'], $fileInfo['imageFile']['tmp_name'], '480', '280'); imagedestroy($fileInfo['imageFile']['tmp_name']); //获取后缀名,这里imageFile为上传表单file控件的name $ext = explode(".", $fileInfo['imageFile']['name']); $ext = $ext[1]; //定义生成目录 $dir = './upload' . date('/Y/m/'); //文件重新命名 do { $filename = date('His') . rand(100000, 999999) . '.' . $ext; } while (file_exists($dir . $filename)); //如果目录不存在则创建目录 if (!file_exists($dir)) { mkdir($dir, 0777, true); } //将图片正式写入 $pass = imagejpeg($filetmp, $dir . '/' . $filename, 100); if (!$pass) { imagedestroy($filetmp); echo "<script>alert('图片资源上传失败,请重新尝试');location.href = '/admin/imageupload';</script>"; exit; } imagedestroy($filetmp); //将图片信息插入数据库 $i = $ArticleMapper->uploadImageInfo($filename, $_SESSION['user']['RealName'], $deptid); if (!isset($i)) { echo "<script>alert('图片信息上传失败,请重新尝试');location.href = '/admin/imageupload';</script>"; exit; } echo "<script>alert('上传成功!');location.href = '/admin/imageupload';</script>"; } else { //加载列表 $DeptMapper = new Application_Model_DepartmentMapper(); $arr = $DeptMapper->findAllDept(); $this->view->arrDept = $arr; $this->view->imageArr = $ArticleMapper->selectImageInfo($_SESSION['user']['RealName']); } }