Новичок
![](./im/images/pips1.gif)
Покинул форум
Сообщений всего: 19
Дата рег-ции: Февр. 2013
Помог: 0 раз(а)
![](./templates/InvisionExBB/im/spacer.gif)
|
Люди, помогите чем сможете. Не знаю в какую сторону копать.
Что имеется:
Имеется загрузчик картинок fancyupload, он заливает на сервер картинку и её уменьшенную копию. Этому всему помогает мутулз, и по моему json. После чего картинки загружаются на сервер а пути к ним сохраняются в базу данных.(это всё работает.)
Что надо:
Надо что бы при загрузке выводилось текстовое поле для введения описания картинки, и после отправки заносилось в базу. Текстовое поле вывел, но после отправки формы записать результат в переменную не получается, проще говоря переменная не посылается к скрипту обработчику.
Вот код формы отправки файла:
CODE ( html):
скопировать код в буфер обмена
<script type="text/javascript"> //<![CDATA[ window.addEvent('domready', function() { // wait for the content // our uploader instance var up = new FancyUpload2($('demo-status'), $('demo-list'), { // options object // we console.log infos, remove that in production!! verbose: false, // url is read from the form, so you just have to change one place url: $('form-demo').action, // path to the SWF file path: '/admin/uploader/source/Swiff.Uploader.swf', // remove that line to select all files, or edit it, add more items typeFilter: { 'Изображения (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png' }, // this is our browse button, *target* is overlayed with the Flash movie target: 'demo-browse', // graceful degradation, onLoad is only called if all went well with Flash onLoad: function() { $('demo-status').removeClass('hide'); // we show the actual UI $('demo-fallback').destroy(); // ... and hide the plain form // We relay the interactions with the overlayed flash to the link this.target.addEvents({ click: function() { return false; }, mouseenter: function() { this.addClass('hover'); }, mouseleave: function() { this.removeClass('hover'); this.blur(); }, mousedown: function() { this.focus(); } }); // Interactions for the 2 other buttons $('demo-clear').addEvent('click', function() { up.remove(); // remove all files return false; }); $('demo-upload').addEvent('click', function() { up.start(); // start upload return false; }); }, // Edit the following lines, it is your custom event handling /** * Is called when files were not added, "files" is an array of invalid File classes. * * This example creates a list of error elements directly in the file list, which * hide on click. */ onSelectFail: function(files) { files.each(function(file) { new Element('li', { 'class': 'validation-error', html: file.validationErrorMessage || file.validationError, title: MooTools.lang.get('FancyUpload', 'removeTitle'), events: { click: function() { this.destroy(); } } }).inject(this.list, 'top'); }, this); }, /** * This one was directly in FancyUpload2 before, the event makes it * easier for you, to add your own response handling (you probably want * to send something else than JSON or different items). */ onFileSuccess: function(file, response) { var json = new Hash(JSON.decode(response, true) || {}); if (json.get('status') == '1') { file.element.addClass('file-success'); file.info.set('html', '<strong>Информация о файле:</strong> ' + json.get('width') + ' x ' + json.get('height') + 'px<br>Новое имя файла: ' + json.get('new') + ''); } else { file.element.addClass('file-failed'); file.info.set('html', '<strong>Ошибка:</strong> ' + json.get('error')); } }, /** * onFail is called when the Flash movie got bashed by some browser plugin * like Adblock or Flashblock. */ onFail: function(error) { switch (error) { case 'hidden': // works after enabling the movie and clicking refresh alert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).'); break; case 'blocked': // This no *full* fail, it works after the user clicks the button alert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).'); break; case 'empty': // Oh oh, wrong path alert('A required file was not found, please be patient and we fix this.'); break; case 'flash': // no flash 9+ :( alert('To enable the embedded uploader, install the latest Adobe Flash plugin.') } } }); }); //]]> </script> <div class="container"> <!-- See index.html --> <div> <form action="/admin/uploader/server/script.php" method="post" enctype="multipart/form-data" id="form-demo"> <fieldset id="demo-fallback"> <legend>Загрузить изображения</legend> <p> В вашем браузере отключено выполнение JavaScript. Для корректной работы требуется включить JavaScript. </p> <label for="demo-photoupload"> Загрузить фото: <input type="file" name="Filedata" /> </label> </fieldset> <div id="demo-status" class="hide"> <p> <a href="#" id="demo-browse">Выбрать файлы</a> | <a href="#" id="demo-clear">Очистить список</a> | <a href="#" id="demo-upload">Начать загрузку</a> </p> <div> <strong class="overall-title"></strong> <img src="/admin/uploader/assets/progress-bar/bar.gif" class="progress overall-progress" /> </div> <div> <strong class="current-title"></strong> <img src="/admin/uploader/assets/progress-bar/bar.gif" class="progress current-progress" /> </div> <ul id="demo-list"></ul> <div class="current-text"></div> </div> </form> </div> </div>
Данные,как видете, передаются в скрипт обработчик script.php:
PHP:
скопировать код в буфер обмена
<?PHP $dblocation = ""; $dbname = ""; $dbuser = ""; $dbpasswd = ""; //Пробую записать пришедшие данные в переменную. $fn = $_POST['fn'];; if (!$dbcnx) { echo "<p>К сожалению, не доступен сервер mySQL</p>"; } { echo "<p>К сожалению, не доступна база данных</p>"; } if(!$ver) { echo "<p>Ошибка в запросе</p>"; } function ImageResize($imgIN,$width,$quality,$imgOUT) { // определяем расширение файла // Загружаем рисунок с диска // создаем переменную для хранения отношения сторон //создаем новый полноцветный пустой рисунок указанной ширины // копируем изображение в созданный файл //imagecopyresampled работает медленнее чем imagecopyresized но качество выше! //imagecopyresized($resnew, $im, 0, 0, 0, 0, $width, $norma*$width, imageSX($im), imageSY($im)); // В конце освобождаем память, занятую картинками } $error = false; //Определяем, был ли файл загружен при помощи HTTP POST $error = 'Invalid Upload'; } //Проверяем размер загружаемых файлов if (!$error && $_FILES['Filedata']['size'] > 15 * 1024 * 1024){ $error = 'Размер загружаемого файла не должен превышать 15 Мб'; } //При желание вы можете добавить другие проверки //Если появились ошибки возвращаем их if ($error) { 'status' => '0', 'error' => $error ); } else { //Если ошибок нет 'status' => '1', 'name' => $_FILES['Filedata']['name'] ); //Получаем информацию о загруженном файле if ($info) { $return['width'] = $info[0];//ширина картинки в пикселях $return['height'] = $info[1];//высота в пиксилях } $filename = $_FILES['Filedata']['name'];//Определяем имя файла $ext = substr($filename,strpos($filename,'.'),strlen($filename)-1 );//Определяем расширение файла $new = date("Ymd")."_".rand(1000 ,9999 ).$ext;//Генерируем новое имя файла во избежании совпадения названий $return['new'] = $new;//Возвращаем имя нового файла if(!move_uploaded_file($_FILES['Filedata']['tmp_name'], '../../../img/'.$new)) //Загружаем файл с новым именем. //Не забудьте установить на каталог uploads права на запись 755 или 777 { 'status' => '0', 'error' => 'Загрузка не удалась' ); } if ($info) { ImageResize('../../../img/'.$new,200,90,'../../../img/pictures/mini/'.$new); ImageResize('../../../img/'.$new,800,90,'../../../img/pictures/'.$new); mysql_query("INSERT INTO imgs (id,year,location,location_mini,title,description,look,date) VALUES (NULL,'1990','/img/pictures/$new','/img/pictures/mini/$new','$fn','Описание','1','')",$dbcnx); } } if (isset($_REQUEST['response']) && $_REQUEST['response'] == 'xml') { // header('Content-type: text/xml'); // Really dirty, use DOM and CDATA section! echo '<response>'; foreach ($return as $key => $value) { echo "<$key><![CDATA[$value]]></$key>"; } echo '</response>'; } else { // header('Content-type: application/json'); } ?>
Так же есть скрипт который после добавления файла создает поле с инфой по файлу, вот кусок из него:
CODE ( javascript):
скопировать код в буфер обмена
this.info = new Element('span', {'class': 'file-info'}); this.element = new Element('li', {'class': 'file'}).adopt( new Element('span', {'class': 'file-size', 'html': Swiff.Uploader.formatUnit(this.size, 'b')}), new Element('a', { 'class': 'file-remove', href: '#', html: MooTools.lang.get('FancyUpload', 'remove'), title: MooTools.lang.get('FancyUpload', 'removeTitle'), events: { click: function() { this.remove(); return false; }.bind(this) } }), new Element('span', {'class': 'file-name', 'html': MooTools.lang.get('FancyUpload', 'fileName').substitute(this)}), new Element('span', {'class': 'file-name', 'html': 'Описание:'}), new Element('input', {'type': 'text', 'class': 'file-title', 'name': 'fn'}), /* Это поле я и создал в надежде что оно будет передавать данные о картинке.*/ this.info ).inject(this.base.list);
Сори за мусорный код, кучу комментариев не стал удалять, может помогут разобраться. Взываю о помощи
|