[ Поиск ] - [ Пользователи ] - [ Календарь ]
Полная Версия: Галерея
Kukaramba
Хочу сделать возможность добавления нескольких фото для каждого из объектов в MySQL. Посоветуйте галерею попроще)



Спустя 9 минут, 22 секунды (17.08.2012 - 09:27) kamanch написал(а):
от написал, так написал...
Давай заново и чтобы понятно было smile.gif

Спустя 43 минуты, 44 секунды (17.08.2012 - 10:10) Kukaramba написал(а):
Ну в общем так. Существует некоторый каталог организаций. Под каждую организацию нужно ставить несколько фото.
Понимаю что нужно создать отдельную таблицу в БД с фото, где будет указана принадлежность к организации и путь к фото. Но вот если готовые решения или хотя бы варианты загрузчиков для такого?

Спустя 9 минут, 24 секунды (17.08.2012 - 10:20) Игорь_Vasinsky написал(а):
может и есть)) ктож искал то..сами пишем чуть что

https://www.google.ru/search?aq=f&sugexp=ch...%80%D0%B5%D0%B8

Спустя 39 минут, 45 секунд (17.08.2012 - 11:00) dron4ik написал(а):
если я правильно понял вопрос, то, х-field нуно)
таблица и ид записи и именем картинки.... по записи и выводим, повторюсь, если я правильно понял вопрос)))

Спустя 2 минуты, 27 секунд (17.08.2012 - 11:02) Акакий написал(а):
А где бы этот x-field глянуть? Интересно.

Спустя 2 дня, 8 часов, 55 минут, 14 секунд (19.08.2012 - 19:57) Kukaramba написал(а):
Хмм.... Нигде не могу найти этот x-field...

Спустя 1 день, 19 часов, 52 минуты, 44 секунды (21.08.2012 - 15:50) dron4ik написал(а):
Цитата (Kukaramba @ 19.08.2012 - 17:57)
Хмм.... Нигде не могу найти этот x-field...

Попробуй "доп поля" поискать!

Спустя 22 часа, 44 минуты, 38 секунд (22.08.2012 - 14:35) Kukaramba написал(а):
Мне понравилась галерея, но у меня возникла проблема сохранения файла. Я пытаюсь создать директорию и в ней - по id, который ловлю по GET - поддиректорию. Скрипт не видит переменную, которую передаю. Подскажите решение.

index

Свернутый текст

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en" xml:lang="en">
<head>
<meta
http-equiv="Content-Type" content="text/html; charset=utf-8">

<script
type="text/javascript" src="source/mootools.js"></script>
<script
type="text/javascript" src="source/Swiff.Uploader.js"></script>
<script
type="text/javascript" src="source/Fx.ProgressBar.js"></script>
<script
type="text/javascript" src="source/Lang.js"></script>
<script
type="text/javascript" src="source/FancyUpload2.js"></script>


<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: '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>
<link
rel="stylesheet" type="text/css" href="source/styles.css">

</head>
<body>



<div
class="container">


<!-- See index.html -->
<div>

<form
action="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><br />
<img
src="assets/progress-bar/bar.gif" class="progress overall-progress" />
</div>
<div>
<strong
class="current-title"></strong><br />
<img
src="assets/progress-bar/bar.gif" class="progress current-progress" />
</div>
<div
class="current-text"></div>
</div>

<ul
id="demo-list"></ul>

</form>
</div>


</div>

<div
class="container quiet" style="line-height: 5em;">

</div>

</body>
</html>



script.php


Свернутый текст
<?php

//Данные для ведения логов
$result = array();

$result['time'] = date('r');
$result['addr'] = substr_replace(gethostbyaddr($_SERVER['REMOTE_ADDR']), '******', 0, 6);
$result['agent'] = $_SERVER['HTTP_USER_AGENT'];

if (count($_GET)) {
$result['get'] = $_GET;
}
if (count($_POST)) {
$result['post'] = $_POST;
}
if (count($_FILES)) {
$result['files'] = $_FILES;
}


if (file_exists('script.log') && filesize('script.log') > 102400) {
unlink('script.log');
}
//Запись данных в лог файл
$log = @fopen('script.log', 'a');
if ($log) {
fputs($log, print_r($result, true) . "\n---\n");
fclose($log);
}

//Изначально у нас нет ошибок
$error = false;

//Определяем, был ли файл загружен при помощи HTTP POST
if (!isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name'])) {
$error = 'Invalid Upload';
}


//Проверяем размер загружаемых файлов
if (!$error && $_FILES['Filedata']['size'] > 2 * 1024 * 1024){
$error = 'Размер загружаемого файла не должен превышать 2 Мб';
}

//При желание вы можете добавить другие проверки



#$imgDir = '../photo/'.$m_id; // каталог для хранения изображений
#@mkdir($imgDir, 0777); // создаем каталог, если его еще нет

$imgDir = 'photo/'.$m_id; // каталог для хранения изображений
@mkdir($imgDir, 0777); // создаем каталог, если его еще нет



//Если появились ошибки возвращаем их

if ($error) {

$return = array(
'status' => '0',
'error' => $error
);

} else {//Если ошибок нет

$return = array(
'status' => '1',
'name' => $_FILES['Filedata']['name']
);


#$mdir = '../upl/';
#$dk = '/1/';

//Получаем информацию о загруженном файле

$info = @getimagesize($_FILES['Filedata']['tmp_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'], $imgDir.$ph_id.'/'.$new)) //Загружаем файл с новым именем.
//Не забудьте установить на каталог uploads права на запись 755 или 777

{
$return = array(
'status' => '0',
'error' => 'Загрузка не удалась'
);
}
}




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');

echo json_encode($return);

}

include 'db_connect.php';
$update = "INSERT INTO `images`
(name,userfile)
VALUES
('
$new','$info')
"
;
$query = mysql_query($update);

?>
Быстрый ответ:

 Графические смайлики |  Показывать подпись
Здесь расположена полная версия этой страницы.
Invision Power Board © 2001-2024 Invision Power Services, Inc.