| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333 |
- <?php
- // @requires $_SERVER['SERVER_NAME']
- Lib::loadClass('RouteBase');
- Lib::loadClass('Response');
- Lib::loadClass('Request');
- Lib::loadClass('UI');
- Lib::loadClass('Http');
- Lib::loadClass('FileStorage');
- /*
- # upload API: `index.php?_route=FileStorage&_task=upload&name={file_name}`
- */
- class Route_FileStorage extends RouteBase {
- public function handleAuth() {
- if (!User::logged()) {
- User::authByRequest();
- }
- }
- public function defaultAction() {
- UI::gora();
- UI::menu();
- try {
- echo '...';
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- UI::dol();
- }
- public function uploadStreamAction() {
- Response::sendTryCatchJson(array($this, 'uploadStreamResponseCallback'));
- }
- public function uploadStreamResponseCallback() {
- $response = array();
- $response['type'] = 'danger';
- $response['msg'] = "Wystąpił nieznany błąd podczas wgrywania pliku";
- $sqlLabel = V::get('name', '', $_REQUEST);
- // read contents from the input stream
- $inputHandler = fopen('php://input', "r");
- $idFile = FileStorage::addFileStream($inputHandler, $sqlLabel);
- $response['id'] = $idFile;
- $fileObject = FileStorage::getFileById($idFile);
- if ($fileObject['exists']) {
- $response['type'] = 'success';
- $response['msg'] = "Wgrano plik nr {$idFile}";
- }
- return $response;
- }
- public function uploadAction() {
- try {
- $fileContent = Request::getRequestBody();
- $sqlLabel = V::get('name', '', $_REQUEST);
- FileStorage::addFile($fileContent, $sqlLabel);
- echo 'file uploaded';
- } catch (Exception $e) {
- echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
- }
- }
- public function uploadFromBinaryTestAction() {
- try {
- $fileContent = Request::getRequestBody();
- $filePath = FileStorage::getRootStoragePath() . '/test-upload-data.txt';
- $fp = fopen($filePath, 'w');
- fwrite($fp, $fileContent);
- fclose($fp);
- echo 'file uploaded?';
- } catch (Exception $e) {
- echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
- }
- }
- public function downloadAction() {
- try {
- $id = V::get('id', 0, $_REQUEST, 'int');
- if ($id <= 0) throw new Exception("Error Wrong file id");
- $fileObject = FileStorage::getFileById($id);
- if (!$fileObject['exists']) throw new HttpException("File not exists", 404);
- header('Content-Description: File Transfer');
- header('Content-Type: ' . $fileObject['mimeType']);
- header('Content-Disposition: attachment; filename="' . $fileObject['name'] . '"');
- header('Expires: 0');
- header('Cache-Control: must-revalidate');
- header('Pragma: public');
- header('Content-Length: ' . $fileObject['size']);
- readfile($fileObject['absolutePath']);
- exit;
- } catch (HttpException $e) {
- Http::sendHeaderByCode($e->getCode());
- die($e->getMessage());
- } catch (Exception $e) {
- die("Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- }
- public function downloadTestAction() {
- try {
- $filePath = FileStorage::getRootStoragePath() . '/test-upload-data.txt';
- if (!file_exists($filePath)) throw new Exception("file not exists!");
- header('Content-Description: File Transfer');
- header('Content-Type: application/octet-stream');
- header('Content-Disposition: attachment; filename="'.basename($filePath).'"');
- header('Expires: 0');
- header('Cache-Control: must-revalidate');
- header('Pragma: public');
- header('Content-Length: ' . filesize($filePath));
- readfile($filePath);
- exit;
- } catch (Exception $e) {
- echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
- }
- }
- public function uploadFromFormTestAction() {
- try {
- // $fileContent = Request::getRequestBody();
- DBG::_(true, true, '_POST', $_POST, __CLASS__, __FUNCTION__, __LINE__);
- // $filePath = FileStorage::getRootStoragePath() . '/test-upload-data.txt';
- // $fp = fopen($filePath, 'w');
- // fwrite($fp, $fileContent);
- // fclose($fp);
- // echo 'file uploaded?';
- } catch (Exception $e) {
- echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
- }
- }
- public function uploadFormTestAction() {
- UI::gora();
- UI::menu();
- try {
- // multiple: <input type="file" id="file_input" multiple="multiple" />
- // only images: <input type="file" id="file_input" multiple="multiple" accept="image/*" />
- ?>
- <div class="container">
- <form>
- <input type="file" id="file_input" style="display:block; width:100%; height:200px; background-color:silver; text-align:center">
- </form>
- <button class="btn btn-primary" id="upload_file_as_stream_btn">upload as stream</button>
- <button class="btn btn-success" id="upload_file_as_binary_btn">upload as binary</button>
- <button class="btn btn-default" id="upload_file_as_form_btn">upload as form</button>
- <a class="btn btn-default" href="index.php?_route=FileStorage&_task=downloadTest" target="_blank">download</a>
- <blockquote>
- <p>root storage path: <code><?php echo FileStorage::getRootStoragePath(); ?></code></p>
- <p>table name: <code><?php echo FileStorage::getTableName(); ?></code></p>
- <p>IP: <code><?php echo Request::getUserIp(); ?></code></p>
- </blockquote>
- </div>
- <?php
- $sqlTblName = FileStorage::getTableName();
- $params = array();
- $params['caption'] = "Files in '{$sqlTblName}'";
- $params['rows'] = array_map(function($row) {
- $row['FILE_SIZE'] = V::humanFileSize($row['FILE_SIZE']);
- unset($row['FILE_HASH']);
- $row['rel_path'] = FileStorage::generateFilePathHashFromId($row['ID']);
- $downloadLink = "index.php?_route=FileStorage&_task=download&id={$row['ID']}";
- $row['download'] = '<a href="' . $downloadLink . '" target="_blank">download</a>';
- return $row;
- }, DB::getPDO()->fetchAll("
- select t.ID
- , t.FILE_HASH
- , t.FILE_LABEL
- , t.FILE_TYPE
- , t.FILE_MIME_TYPE
- , t.FILE_MTIME
- , t.FILE_SIZE
- , t.FILE_VERSION
- , t.A_STATUS
- , t.A_RECORD_CREATE_DATE as created
- , t.A_RECORD_CREATE_AUTHOR as author
- , t.A_RECORD_UPDATE_DATE as updated
- , t.A_RECORD_UPDATE_AUTHOR as editor
- , t.A_ADM_COMPANY as zapisDla
- , t.A_CLASSIFIED as odczytDla
- , INET_NTOA(t.A_USER_IP) as IP
- from `{$sqlTblName}` t
- order by ID DESC
- limit 100
- "));
- UI::table($params);
- ?>
- <script>
- document.getElementById('file_input').addEventListener('change', function() {
- for (var i = 0; i < this.files.length; i++){
- var file = this.files[i];
- // This code is only for demo ...
- console.group("File "+i);
- console.log("name : " + file.name);
- console.log("size : " + file.size);
- console.log("type : " + file.type);
- console.log("date : " + file.lastModified);
- console.groupEnd();
- }
- }, false);
- function uploadFileAsForm(file) {
- var serverUrl = '<?php echo Request::getPathUri() . "index.php?_route=FileStorage&_task=uploadFromFormTest"; ?>';
- var xhr = new XMLHttpRequest();
- var fd = new FormData();
- xhr.open("POST", serverUrl, true);
- xhr.onreadystatechange = function() {
- if (xhr.readyState == 4 && xhr.status == 200) {
- // Every thing ok, file uploaded
- console.log(xhr.responseText); // handle response.
- }
- };
- fd.append("upload_file", file);
- xhr.send(fd);
- }
- function uploadFileAsStream(file) {
- var serverUrl = '<?php echo Request::getPathUri() . "index.php?_route=FileStorage&_task=uploadStream"; ?>';
- var _dbg = true;
- // .set('Accept', 'application/json')
- superagent.post(serverUrl + '&name=' + file.name)
- .set('Content-Type', file.type)
- .send(file)
- .end(function(err, res) {
- if(_dbg)console.log('DBG: res:', res, 'res.body:', res.body);
- if (res.status != 200) {
- jQuery.notify("Wystąpił błąd: " + res.text, 'error')
- } else if (res.body && res.body.msg && res.body.type) {
- var notifyType = ('danger' == res.body.type) ? 'error' : res.body.type;
- jQuery.notify(res.body.msg, notifyType)
- } else if (res.body && res.body.id && res.body.id > 0) {
- jQuery.notify("Wgrano plik:" + JSON.stringify(res.body), 'success')
- } else {
- jQuery.notify("Wystąpił błąd: " + JSON.stringify(res.body), 'error')
- }
- })
- }
- function uploadFileAsBinary(file) {
- var serverUrl = '<?php echo Request::getPathUri() . "index.php?_route=FileStorage&_task=upload"; ?>';
- var _dbg = true;
- // .set('Accept', 'application/json')
- superagent.post(serverUrl + '&name=' + file.name)
- .set('Content-Type', file.type)
- .send(file)
- .end(function(err, res) {
- if(_dbg)console.log('DBG: res:', res, 'res.body:', res.body);
- })
- return
- jQuery.ajax({
- type: "POST",
- beforeSend: function (request) {
- request.setRequestHeader("Content-Type", file.type);
- },
- url: serverUrl,
- data: file,
- processData: false,
- contentType: false,
- success: function (data) {
- console.log("File available at: ", data);
- },
- error: function (data) {
- var obj = jQuery.parseJSON(data);
- alert(obj.error);
- }
- })
- }
- jQuery('#upload_file_as_stream_btn').on('click', function() {
- var fileInput = document.getElementById('file_input')
- if (!fileInput) return false;// TODO: error msg
- if (!fileInput.files) return false;// TODO: error msg
- if (!fileInput.files.length) return false;// TODO: error msg
- var fileInfo = fileInput.files[0];
- console.log('fileInfo', fileInfo);
- uploadFileAsStream(fileInfo);
- });
- jQuery('#upload_file_as_binary_btn').on('click', function() {
- var fileInput = document.getElementById('file_input')
- if (!fileInput) return false;// TODO: error msg
- if (!fileInput.files) return false;// TODO: error msg
- if (!fileInput.files.length) return false;// TODO: error msg
- var fileInfo = fileInput.files[0];
- console.log('fileInfo', fileInfo);
- uploadFileAsBinary(fileInfo);
- });
- jQuery('#upload_file_as_form_btn').on('click', function() {
- var fileInput = document.getElementById('file_input')
- if (!fileInput) return false;// TODO: error msg
- if (!fileInput.files) return false;// TODO: error msg
- if (!fileInput.files.length) return false;// TODO: error msg
- var fileInfo = fileInput.files[0];
- console.log('fileInfo', fileInfo);
- uploadFileAsForm(fileInfo);
- });
- </script>
- <?php
- } catch (Exception $e) {
- UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- UI::dol();
- }
- public function generatePathTestAction() {
- try {
- $start = 0;
- $start = 446071;
- $limit = $start + 100;
- echo '<pre>';
- for ($i = $start; $i < $limit; $i++) {
- FileStorage::generateFilePathHashFromId($i);
- }
- echo '</pre>';
- } catch (Exception $e) {
- echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
- }
- }
- public function reinstallAction() {
- UI::gora();
- UI::menu();
- FileStorage::reinstall();
- UI::dol();
- }
- }
|