Сегодня поделюсь своей наработкой по загрузке изображений и последующей сортировке.
Для загрузки есть готовое решение: http://www.uploadify.com/demos/
Вот с помощью неё мы и организовали загрузку, но с маленькими ухищрениями, они нужны были для моих целей.
index.php — основной рабочий файл.
<link href="/uploadify/uploadify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="/uploadify/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/uploadify/swfobject.js"></script>
<script type="text/javascript" src="/uploadify/jquery.uploadify.v2.1.4.min.js"></script>
<script type="text/javascript">
$(function() {
$.post
(
"show_gall.php",
{
id : '2'
},
function(data) {
$('#picasso').html(data);
}
);
$('#custom_file_upload').uploadify({
'uploader' : '/uploadify/uploadify.swf',
'script' : '/uploadify/uploadify.php?id=2',
'cancelImg' : '/uploadify/cancel.png',
'folder' : '/uploads',
'multi' : true,
'auto' : true,
'fileExt' : '*.jpg;*.gif;',
'fileDesc' : 'Image Files (.JPG, .GIF)',
'queueID' : 'custom-queue',
'removeCompleted': true,
'onSelectOnce' : function(event,data) {
$('#status-message').text(data.filesSelected + ' files have been added to the queue.');
},
'onAllComplete' : function(event,data) {
$.post
(
"show_gall.php",
{
id : 2
},
function(data) {
$('#picasso').html(data);
}
);
}
}); });
function del(id){
if (id > 0){
$.post
(
"del_img.php",
{
id : id
},
function(data) {
$.post
(
"show_gall.php",
{
id : '2'
},
function(data) {
$('#picasso').html(data);
}
);
}
);
}
}
</script>
<style type="text/css">
#custom-demo .uploadifyQueueItem {
background-color: #FFFFFF;
border: none;
border-bottom: 1px solid #E5E5E5;
font: 11px Verdana, Geneva, sans-serif;
height: 50px;
margin-top: 0;
padding: 10px;
width: 350px;
}
#custom-demo .uploadifyError {
background-color: #FDE5DD !important;
border: none !important;
border-bottom: 1px solid #FBCBBC !important;
}
#custom-demo .uploadifyQueueItem .cancel {
float: right;
}
#custom-demo .uploadifyQueue .completed {
color: #C5C5C5;
}
#custom-demo .uploadifyProgress {
background-color: #E5E5E5;
margin-top: 10px;
width: 100%;
}
#custom-demo .uploadifyProgressBar {
background-color: #0099FF;
height: 3px;
width: 1px;
}
#custom-demo #custom-queue {
border: 1px solid #E5E5E5;
height: 213px;
margin-bottom: 10px;
width: 370px;
} </style>
<div>
<div id="status-message">Select some files to upload:</div>
<div id="custom-queue"></div>
<input id="custom_file_upload" type="file" name="Filedata" /> </div>
</div>
</div>
<div id="picasso">s</div>
В функциях jQuery код, который получает данные из базы о фотках повторяется. Нужно этот код вывести в отдельную функцию.
Теперь, про параметр id: В примере он принимает статическое значение, но на практике оно будет меняться динамически. Это нужно, чтобы фотографии можно было привязать к различным страницам.
Информацию о порядке отображения изображений я буду хранить в базе данных.
CREATE TABLE IF NOT EXISTS `img` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`pic` varchar(255) NOT NULL,
`pr` int(10) NOT NULL,
`parent_id` int(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=cp1251 AUTO_INCREMENT=21 ;
Теперь займемся настройкой файла загрузки изображения.
uploadify/uploadify.php
<?php
if (!empty($_FILES)) {
require '../config/db.php';
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'.$_GET['id'].'/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
mkdir(str_replace('//','/',$targetPath), 0755, true);
move_uploaded_file($tempFile,$targetFile);
$q = "insert into img set
pic = '".$_FILES['Filedata']['name']."',
parent_id = '".intval($_GET['id'])."',
pr = '0'";
mysql_query($q);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
}
?>
С помощью id мы разделяем фотографии с различных страниц в различные папки. Можно вставить еще кроп изображений, проверку на наличие — всё это по вашему вкусу.
Теперь перейдём к отображению и сортировке изображений:
show_gall.php
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
#sortable { list-style-type: none; margin: 0; padding: 0; }
#sortable li { margin: 3px 3px 0 0; padding: 1px; float: left; width: 55px; height: 55px; text-align: center; }
#sortable li img {padding:1px; border:1px solid #ccc; cursor: pointer; width:50px; height:50px;}
.ui-state-default, .ui-widget-content .ui-state-default{border:none; background:none;}
.clear {clear:both;}
</style>
<div id="reorder-gallery">
<ul id="sortable">
<?
require_once 'config/db.php';
$id = (int) $_POST['id'];
$q = "Select * from img where parent_id = '".$id."' order by pr ";
$r = mysql_query($q);
while ($row = mysql_fetch_array($r)){
echo '<li id="'.$row['id'].'"><img src="uploads/'.$row['parent_id'].'/'.$row['pic'].'"/><a href="javascript:;" onClick="del('.$row['id'].');">x</a></li>';
}
?>
</ul>
<div></div>
<script>var imgOrder = '';
$(function() {
$("#sortable").sortable({
update: function(event, ui) {
imgOrder = $("#sortable").sortable('toArray').toString();
$.post
(
"update.php",
{
c : imgOrder
},
function(data) {
}
);
}
});
$("#sortable").disableSelection();
});
$(document).ready(function(){
$("#btnshoworder").click(function(){
alert(imgOrder);
});
});
</script>
Сортировка выполняется с помощью функции jQuery UI sortable(), дальше выполняется обновление в базе порядка сортировки.
|
download: sortable_multiupload (231.47KB)
added: 09/11/2010
clicks: 362
description: Мультиаплоад и сортировка изображений на лету.
|