Warning: Cannot use a scalar value as an array in /home/admin/public_html/forum/include/fm.class.php on line 757

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/include/fm.class.php on line 770
Форумы портала PHP.SU :: Версия для печати :: Помогите с загрузкой файла.
Форумы портала PHP.SU » » Если скрипт не работает » Помогите с загрузкой файла.

Страниц (1): [1]
 

1. Allegamex - 06 Марта, 2013 - 07:29:47 - перейти к сообщению
Люди, помогите чем сможете. Не знаю в какую сторону копать.
Что имеется:
Имеется загрузчик картинок fancyupload, он заливает на сервер картинку и её уменьшенную копию. Этому всему помогает мутулз, и по моему json. После чего картинки загружаются на сервер а пути к ним сохраняются в базу данных.(это всё работает.)
Что надо:
Надо что бы при загрузке выводилось текстовое поле для введения описания картинки, и после отправки заносилось в базу. Текстовое поле вывел, но после отправки формы записать результат в переменную не получается, проще говоря переменная не посылается к скрипту обработчику.

Вот код формы отправки файла:
CODE (html):
скопировать код в буфер обмена
  1.  <script type="text/javascript">
  2.  
  3.                 //<![CDATA[
  4.  
  5. window.addEvent('domready', function() { // wait for the content
  6.  
  7.         // our uploader instance
  8.        
  9.         var up = new FancyUpload2($('demo-status'), $('demo-list'), { // options object
  10.                 // we console.log infos, remove that in production!!
  11.                 verbose: false,
  12.                
  13.                 // url is read from the form, so you just have to change one place
  14.                 url: $('form-demo').action,
  15.                
  16.                 // path to the SWF file
  17.                 path: '/admin/uploader/source/Swiff.Uploader.swf',
  18.                
  19.                 // remove that line to select all files, or edit it, add more items
  20.                 typeFilter: {
  21.                         'Изображения (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png'
  22.                 },
  23.                
  24.                 // this is our browse button, *target* is overlayed with the Flash movie
  25.                 target: 'demo-browse',
  26.                
  27.                 // graceful degradation, onLoad is only called if all went well with Flash
  28.                 onLoad: function() {
  29.                         $('demo-status').removeClass('hide'); // we show the actual UI
  30.                         $('demo-fallback').destroy(); // ... and hide the plain form
  31.                        
  32.                         // We relay the interactions with the overlayed flash to the link
  33.                         this.target.addEvents({
  34.                                 click: function() {
  35.                                         return false;
  36.                                 },
  37.                                 mouseenter: function() {
  38.                                         this.addClass('hover');
  39.                                 },
  40.                                 mouseleave: function() {
  41.                                         this.removeClass('hover');
  42.                                         this.blur();
  43.                                 },
  44.                                 mousedown: function() {
  45.                                         this.focus();
  46.                                 }
  47.                         });
  48.  
  49.                         // Interactions for the 2 other buttons
  50.                        
  51.                         $('demo-clear').addEvent('click', function() {
  52.                                 up.remove(); // remove all files
  53.                                 return false;
  54.                         });
  55.  
  56.                         $('demo-upload').addEvent('click', function() {
  57.                                 up.start(); // start upload
  58.                                 return false;
  59.                         });
  60.                 },
  61.                
  62.                 // Edit the following lines, it is your custom event handling
  63.                
  64.                 /**
  65.                  * Is called when files were not added, "files" is an array of invalid File classes.
  66.                  *
  67.                  * This example creates a list of error elements directly in the file list, which
  68.                  * hide on click.
  69.                  */
  70.                 onSelectFail: function(files) {
  71.                         files.each(function(file) {
  72.                                 new Element('li', {
  73.                                         'class': 'validation-error',
  74.                                         html: file.validationErrorMessage || file.validationError,
  75.                                         title: MooTools.lang.get('FancyUpload', 'removeTitle'),
  76.                                         events: {
  77.                                                 click: function() {
  78.                                                         this.destroy();
  79.                                                 }
  80.                                         }
  81.                                 }).inject(this.list, 'top');
  82.                         }, this);
  83.                 },
  84.                
  85.                 /**
  86.                  * This one was directly in FancyUpload2 before, the event makes it
  87.                  * easier for you, to add your own response handling (you probably want
  88.                  * to send something else than JSON or different items).
  89.                  */
  90.                 onFileSuccess: function(file, response) {
  91.                         var json = new Hash(JSON.decode(response, true) || {});
  92.                        
  93.                         if (json.get('status') == '1') {
  94.                                 file.element.addClass('file-success');
  95.                                 file.info.set('html', '<strong>Информация о файле:</strong> ' + json.get('width') + ' x ' + json.get('height') + 'px<br>Новое имя файла: ' + json.get('new') + '');
  96.                         } else {
  97.                                 file.element.addClass('file-failed');
  98.                                 file.info.set('html', '<strong>Ошибка:</strong> ' + json.get('error'));
  99.                         }
  100.                 },
  101.                
  102.                 /**
  103.                  * onFail is called when the Flash movie got bashed by some browser plugin
  104.                  * like Adblock or Flashblock.
  105.                  */
  106.                 onFail: function(error) {
  107.                         switch (error) {
  108.                                 case 'hidden': // works after enabling the movie and clicking refresh
  109.                                         alert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).');
  110.                                         break;
  111.                                 case 'blocked': // This no *full* fail, it works after the user clicks the button
  112.                                         alert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).');
  113.                                         break;
  114.                                 case 'empty': // Oh oh, wrong path
  115.                                         alert('A required file was not found, please be patient and we fix this.');
  116.                                         break;
  117.                                 case 'flash': // no flash 9+ :(
  118.                                         alert('To enable the embedded uploader, install the latest Adobe Flash plugin.')
  119.                         }
  120.                 }
  121.                
  122.         });
  123.        
  124. });
  125.                 //]]>
  126.         </script>               <div class="container">
  127.                 <!-- See index.html -->
  128.                 <div>
  129.                         <form action="/admin/uploader/server/script.php" method="post" enctype="multipart/form-data" id="form-demo">
  130.  
  131.         <fieldset id="demo-fallback">
  132.                 <legend>Загрузить изображения</legend>
  133.                 <p>
  134.                         В вашем браузере отключено выполнение JavaScript. Для корректной работы требуется включить JavaScript.
  135.                 </p>
  136.                 <label for="demo-photoupload">
  137.                         Загрузить фото:
  138.                         <input type="file" name="Filedata" />
  139.                 </label>
  140.         </fieldset>
  141.  
  142.         <div id="demo-status" class="hide">
  143.                 <p>
  144.                         <a href="#" id="demo-browse">Выбрать файлы</a> |
  145.                         <a href="#" id="demo-clear">Очистить список</a> |
  146.                         <a href="#" id="demo-upload">Начать загрузку</a>
  147.                 </p>
  148.                 <div>
  149.                         <strong class="overall-title"></strong>                 <img src="/admin/uploader/assets/progress-bar/bar.gif" class="progress overall-progress" />
  150.                 </div>
  151.                 <div>
  152.                         <strong class="current-title"></strong>                 <img src="/admin/uploader/assets/progress-bar/bar.gif" class="progress current-progress" />
  153.                 </div>
  154.                 <ul id="demo-list"></ul>
  155.    
  156.     <div class="current-text"></div>
  157.         </div>
  158.  
  159.        
  160.  
  161. </form>
  162. </div>
  163.         </div>
  164.  



Данные,как видете, передаются в скрипт обработчик script.php:
PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3. $dblocation = "";  
  4. $dbname = "";  
  5. $dbuser = "";  
  6. $dbpasswd = "";
  7. $dbcnx = @mysql_connect($dblocation, $dbuser, $dbpasswd);
  8. //Пробую записать пришедшие данные в переменную.
  9. $fn = $_POST['fn'];;
  10.   if (!$dbcnx)  
  11.   {  
  12.     echo "<p>К сожалению, не доступен сервер mySQL</p>";  
  13.     exit();  
  14.   }  
  15.   if (!@mysql_select_db($dbname,$dbcnx) )  
  16.   {  
  17.     echo "<p>К сожалению, не доступна база данных</p>";  
  18.     exit();  
  19.   }  
  20.   $ver = mysql_query("SELECT VERSION()");  
  21.   if(!$ver)  
  22.   {  
  23.     echo "<p>Ошибка в запросе</p>";  
  24.     exit();  
  25.   }
  26. function ImageResize($imgIN,$width,$quality,$imgOUT)
  27.  {
  28.         // определяем расширение файла
  29.         $ext = strtolower(substr($imgIN,-3));
  30.         $name = strtolower(substr($imgIN,0,strlen($imgIN)-4));
  31.         // Загружаем рисунок с диска
  32.         if ($ext=='png')$im = imageCreateFromPng($imgIN);
  33.         if ($ext=='gif')$im = imageCreateFromGif($imgIN);
  34.         if ($ext=='jpg')$im = imageCreateFromJpeg($imgIN);
  35.         // создаем переменную для хранения отношения сторон
  36.         $norma=(int)imageSY($im)/imageSX($im);
  37.         //создаем новый полноцветный пустой рисунок указанной ширины
  38.         $resnew = imagecreatetruecolor($width, $width*$norma);
  39.         imagealphablending($resnew,true);
  40.        
  41.         // копируем изображение в созданный файл
  42.             //imagecopyresampled работает медленнее чем imagecopyresized но качество выше!
  43.         //imagecopyresized($resnew, $im, 0, 0, 0, 0, $width, $norma*$width, imageSX($im), imageSY($im));
  44.         imagecopyresampled($resnew, $im, 0, 0, 0, 0, $width, $norma*$width, imageSX($im), imageSY($im));
  45.        
  46.         imagejpeg($resnew,$imgOUT,$quality);
  47.         // В конце освобождаем память, занятую картинками
  48.         imageDestroy($im);
  49.         imageDestroy($resnew);
  50.  }
  51. $error = false;
  52.  
  53. //Определяем, был ли файл загружен при помощи HTTP POST
  54. if (!isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name'])) {
  55.         $error = 'Invalid Upload';
  56. }
  57.  
  58.  
  59. //Проверяем размер загружаемых файлов
  60. if (!$error && $_FILES['Filedata']['size'] > 15 * 1024 * 1024){
  61.         $error = 'Размер загружаемого файла не должен превышать 15 Мб';
  62. }
  63.  
  64. //При желание вы можете добавить другие проверки
  65.  
  66. //Если появились ошибки возвращаем их
  67. if ($error) {
  68.  
  69.         $return = array(
  70.                 'status' => '0',
  71.                 'error' => $error
  72.         );
  73.  
  74. } else {
  75. //Если ошибок нет
  76.  
  77.         $return = array(
  78.                 'status' => '1',
  79.                 'name' => $_FILES['Filedata']['name']
  80.         );
  81.  
  82.         //Получаем информацию о загруженном файле
  83.         $info = getimagesize($_FILES['Filedata']['tmp_name']);
  84.  
  85.         if ($info) {
  86.                 $return['width'] = $info[0];//ширина картинки в пикселях
  87.                 $return['height'] = $info[1];//высота в пиксилях
  88.  
  89.         }
  90.         $filename = $_FILES['Filedata']['name'];//Определяем имя файла
  91.         $ext = substr($filename,strpos($filename,'.'),strlen($filename)-1);//Определяем расширение файла
  92.         $new = date("Ymd")."_".rand(1000,9999).$ext;//Генерируем новое имя файла во избежании совпадения названий
  93.         $return['new'] = $new;//Возвращаем имя нового файла
  94.         if(!move_uploaded_file($_FILES['Filedata']['tmp_name'], '../../../img/'.$new)) //Загружаем файл с новым именем.
  95.         //Не забудьте установить на каталог uploads права на запись 755 или 777
  96.         {    
  97.                 $return = array(
  98.                 'status' => '0',
  99.                 'error' => 'Загрузка не удалась'
  100.                 );
  101.         }
  102.  
  103.   if ($info) {
  104.     ImageResize('../../../img/'.$new,200,90,'../../../img/pictures/mini/'.$new);
  105.     ImageResize('../../../img/'.$new,800,90,'../../../img/pictures/'.$new);
  106.     unlink('../../../img/'.$new);
  107.     mysql_query("SET NAMES utf8");
  108.     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);    
  109.  
  110.   }
  111. }
  112. if (isset($_REQUEST['response']) && $_REQUEST['response'] == 'xml') {
  113.         // header('Content-type: text/xml');
  114.  
  115.         // Really dirty, use DOM and CDATA section!
  116.         echo '<response>';
  117.         foreach ($return as $key => $value) {
  118.                 echo "<$key><![CDATA[$value]]></$key>";
  119.         }
  120.         echo '</response>';
  121. } else {
  122.         // header('Content-type: application/json');
  123.  
  124.         echo json_encode($return);
  125.  
  126. }
  127.      
  128. ?>
  129.  


Так же есть скрипт который после добавления файла создает поле с инфой по файлу, вот кусок из него:

CODE (javascript):
скопировать код в буфер обмена
  1.  
  2. this.info = new Element('span', {'class': 'file-info'});
  3.                 this.element = new Element('li', {'class': 'file'}).adopt(
  4.       new Element('span', {'class': 'file-size', 'html': Swiff.Uploader.formatUnit(this.size, 'b')}),                  
  5.       new Element('a', {
  6.                                 'class': 'file-remove',
  7.                                 href: '#',
  8.                                 html: MooTools.lang.get('FancyUpload', 'remove'),
  9.                                 title: MooTools.lang.get('FancyUpload', 'removeTitle'),
  10.                                 events: {
  11.                                         click: function() {
  12.                                                 this.remove();
  13.                                                 return false;
  14.                                         }.bind(this)
  15.                                 }
  16.                         }),      
  17.                         new Element('span', {'class': 'file-name', 'html': MooTools.lang.get('FancyUpload', 'fileName').substitute(this)}),
  18.       new Element('span', {'class': 'file-name', 'html': 'Описание:'}),
  19.       new Element('input', {'type': 'text', 'class': 'file-title', 'name': 'fn'}), /* Это поле я и создал в надежде что оно будет передавать данные о картинке.*/
  20.                         this.info
  21.                 ).inject(this.base.list);
  22.  


Сори за мусорный код, кучу комментариев не стал удалять, может помогут разобраться. Взываю о помощи Улыбка

 

Powered by ExBB FM 1.0 RC1