Exemple #1
0
 /**
  * 檔案上傳
  * @param $data
  * @param $pageRes \Base\Entity\Page
  * @return JsonModel
  */
 public function saveFile($data, $pageRes)
 {
     $jsonModel = new JsonModel();
     $em = $this->getEntityManager();
     $form = new PageFileForm();
     $form->bind($pageRes);
     $form->setData($data);
     if ($form->isValid()) {
         $adapter = new \Zend\File\Transfer\Adapter\Http();
         if (!$adapter->isUploaded() and !isset($data['updateId'])) {
             // 排除修改狀態
             $jsonModel->setVariable('success', false);
             $jsonModel->setVariable('message', array('upload_file[]' => array('no_file', '沒有上傳檔案')));
             return $jsonModel;
         }
         $em->persist($pageRes);
         $em->flush();
         // 檔案部份
         $tempId = sprintf("%02x", rand(1000, 2000));
         $len = (int) strlen($tempId) / 2;
         $path = '';
         for ($i = 0; $i < $len - 1; $i++) {
             $path .= substr($tempId, $i * 2, 2) . '/';
         }
         $filePath = $this->FileStorePath('cms/' . $path);
         $config = $this->getServiceLocator()->get('config');
         $adapter->addValidator('Extension', false, $config['upload']['allow_type']);
         $i = 1;
         foreach ($adapter->getFileInfo() as $media) {
             $ext = $this->_findexts($media['name']);
             $ss = 'p' . $i . '-' . time();
             $fileName = $ss . '.' . $ext;
             $adapter->addFilter('Rename', array('source' => $media['tmp_name'], 'target' => $filePath . $fileName, 'overwrite' => true));
             if (!$adapter->receive($media['name'])) {
                 $jsonModel->setVariable('success', false);
                 $jsonModel->setVariable('message', $adapter->getMessages());
                 return $jsonModel;
             } else {
                 $pageFile = new \Base\Entity\PageFile();
                 $pageFile->setPage($pageRes);
                 $pageFile->setFileExt($ext);
                 $pageFile->setFileName($path . $fileName);
                 $pageFile->setFileSize($media['size']);
                 $pageFile->setSourceName($media['name']);
                 $em->persist($pageFile);
             }
             $i++;
         }
         $em->flush();
         $jsonModel->setVariable('success', true);
     } else {
         $jsonModel->setVariable('success', false);
         $jsonModel->setVariable('message', $form->getMessages());
     }
     // tags
     if ($data['tags']) {
         $this->setTags($data, $pageRes);
     }
     return $jsonModel;
 }
 public function processjqueryAction()
 {
     $form = new \Users\Form\UploadJqueryForm();
     //        $form->setInputFilter(new \Users\Form\Filter\UploadJqueryFilter());
     $request = $this->getRequest();
     $response = $this->getResponse();
     $jsonModel = new \Zend\View\Model\JsonModel();
     try {
         if ($request->isPost()) {
             $data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray());
             //                throw new \Exception(json_encode("data " . serialize($data)));
             $form->setData($data);
             if ($form->isValid()) {
                 $datas = [];
                 $datas['files'] = [];
                 $uploadPath = $this->getFileUploadLocation();
                 //                $uploadFiles    = $this->params()->fromFiles('files');
                 //                throw new \Exception(json_encode("FILES " . serialize($_FILES)));
                 // Сохранение выгруженного файла
                 $adapter = new \Zend\File\Transfer\Adapter\Http();
                 $adapter->setDestination($uploadPath);
                 $adapter->setValidators(array(new \Zend\Validator\File\Extension(array('extension' => array('jpg', 'jpeg', 'png', 'rtf')))));
                 //                    $adapter->setFilters(array(
                 //                        new \Zend\Filter\File\RenameUpload(array(
                 //                            'target'    => $uploadPath . '../tmpuploads/tmp',
                 //                            'randomize' => true,
                 //                                )
                 //                        )
                 //                    ));
                 if (!$adapter->isValid()) {
                     throw new \Exception(json_encode("!isValid " . implode(" ", $adapter->getMessages())));
                 }
                 $files = $adapter->getFileInfo();
                 //                throw new \Exception(json_encode($files));
                 foreach ($files as $file => $info) {
                     //                    throw new \Exception(json_encode($info));
                     $name = $adapter->getFileName($file);
                     // file uploaded & is valid
                     if (!$adapter->isUploaded($file)) {
                         throw new \Exception(json_encode("!isUploaded") . implode(" ", $adapter->getMessages()));
                         continue;
                     }
                     if (!$adapter->isValid($file)) {
                         throw new \Exception(json_encode("!isValid " . implode(" ", $adapter->getMessages())));
                         continue;
                     }
                     // receive the files into the user directory
                     $check = $adapter->receive($file);
                     // this has to be on top
                     if (!$check) {
                         throw new \Exception(json_encode("! receive" . implode(" ", $adapter->getMessages())));
                     }
                     /**
                     * "name": "picture1.jpg",
                      "size": 902604,
                      "url": "http:\/\/example.org\/files\/picture1.jpg",
                      "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg",
                      "deleteUrl": "http:\/\/example.org\/files\/picture1.jpg",
                      "deleteType": "DELETE"
                     */
                     $fileclass = new stdClass();
                     // we stripped out the image thumbnail for our purpose, primarily for security reasons
                     // you could add it back in here.
                     $fileclass->name = $name;
                     $fileclass->size = $adapter->getFileSize($name);
                     $fileclass->type = $adapter->getMimeType($name);
                     $fileclass->deleteUrl = '/uploads/delete';
                     $fileclass->deleteType = 'DELETE';
                     //$fileclass->error = 'null';
                     $fileclass->url = '/';
                     $datas['files'][] = $fileclass;
                 }
                 $response->getHeaders()->addHeaders(array('Pragma' => 'no-cache', 'Cache-Control' => 'private, no-cache', "Content-Type" => 'application/json'));
                 //                return $response->setContent(json_encode(array('files' => $files)));
                 return $response->setContent(json_encode($datas));
             } else {
                 throw new \Exception(json_encode("!isValid form" . serialize($form->getMessages())));
             }
         }
     } catch (\Exception $e) {
         return $response->setContent(json_encode($e->getMessage()));
     }
     return $jsonModel;
     //        if ($request->isPost()) {
     //                // Получение конфигурации из конфигурационных данных модуля
     //                $uploadPath = $this->getFileUploadLocation();
     //
     //                // Сохранение выгруженного файла
     //                $adapter = new \Zend\File\Transfer\Adapter\Http();
     //                $adapter->setDestination($uploadPath);
     //                if ($adapter->receive($uploadFile['name'])) {
     //
     //                    $userTable = $this->getServiceLocator()->get('UserTable');
     //                    $user      = $userTable->getUserByEmail($userEmail);
     //
     //                    $upload = new \Users\Model\Upload();
     //
     //                    // Успешная выгрузка файла
     //                    $exchange_data             = array();
     //                    $exchange_data['label']    = $request->getPost()->get('label');
     //                    $exchange_data['filename'] = $uploadFile['name'];
     //                    $exchange_data['user_id']  = $user->getId();
     //                    $upload->exchangeArray($exchange_data);
     //
     //                    $uploadTable = $this->getServiceLocator()->get('UploadTable');
     //                    $uploadTable->save($upload);
     //                    $upload->setId($uploadTable->getLastInsertValue());
     //
     //                    //добавить в Lucene
     //                    $searchIndexLocation = $this->getIndexLocation();
     //                    $index               = Lucene\Lucene::create($searchIndexLocation);
     //
     //                    // создание полей lucene
     //                    $fileUploadId = Document\Field::unIndexed(
     //                                    'upload_id', $upload->getId());
     //                    $label        = Document\Field::Text('label', $upload->getLabel());
     //                    $owner        = Document\Field::Text('owner', $user->getName());
     //
     //                    $uploadPath = $this->getFileUploadLocation();
     //                    $fileName   = $upload->getFilename();
     //                    $filePath   = $uploadPath . DIRECTORY_SEPARATOR . $fileName;
     //
     //                    if (substr_compare($fileName, ".xlsx", strlen($fileName) -
     //                                    strlen(".xlsx"), strlen(".xlsx")) === 0) {
     //                        // Индексирование таблицы excel
     //                        $indexDoc = Lucene\Document\Xlsx::loadXlsxFile($filePath);
     //                    } else if (substr_compare($fileName, ".docx", strlen($fileName) -
     //                                    strlen(".docx"), strlen(".docx")) === 0) {
     //                        // Индексирование документа Word
     //                        $indexDoc = Lucene\Document\Docx::loadDocxFile($filePath);
     //                    } else {
     //                        $indexDoc = new Lucene\Document();
     //                    }
     //
     //                    // создание нового документа и добавление всех полей
     //                    $indexDoc = new Lucene\Document();
     //                    $indexDoc->addField($label);
     //                    $indexDoc->addField($owner);
     //                    $indexDoc->addField($fileUploadId);
     //                    $index->addDocument($indexDoc);
     //
     //                    $index->commit();
     //                }
     //        }
     //        return $response->setContent("");
 }