本帖最后由 cuihaifeng1234 于 2016-1-15 09:25 编辑
前些日子做的多图发现IE竟然不兼容,WebUploader官方的例子也是,IE下根本点不开。所以自己今天改写一下,并在默认模版的基础上增加了这个功能。在这里详细来说明一下步骤:1.系统采用plupload来作为一个上传工具,话不多了,请大家自行下载此插件(依赖Jquery)
2.下载成功后我们将下载来的js放到网站admin目录下
3.在admin/templates/product.html导入所需要的js文件
- <!-- 上传组件 -->
- <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css" type="text/css" />
- <link rel="stylesheet" href="js/jquery.ui.plupload/css/jquery.ui.plupload.css" type="text/css" />
- <!-- 上传组件 -->
- <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
- <!-- production -->
- <script type="text/javascript" src="js/plupload.full.min.js"></script>
- <script type="text/javascript" src="js/jquery.ui.plupload/jquery.ui.plupload.js"></script>
- <script type="text/javascript" src="js/i18n/zh_CN.js"></script>
复制代码 4.在product.htm 190行的位置添加如下代码:
- <!-- 图集上传 -->
- <tr>
- <td>产品图集上传(编辑商品图集上传会覆盖掉产品的图集,建议一次性上传)</td>
- <td>
- <div id="uploader">
- <p>Your browser doesn't have Flash, Silverlight or HTML5 support.</p>
- </div>
- </td>
- </tr>
复制代码
5.初始化上传组件,加到文件最后就可以
- {literal}
- <script type="text/javascript">
- // 初始化上传组件
- $(function() {
- $("#uploader").plupload({
- // 设置
- runtimes : 'html5,flash,silverlight,html4',
- url : 'upload.php',
- // 最大上传数量
- max_file_count: 20,
-
- chunk_size: '1mb',
- // 客户端看到的缩略图
- resize : {
- width : 800,
- height : 600,
- quality : 90,
- crop: true // crop to exact dimensions
- },
-
- filters : {
- // 最大上传文件
- max_file_size : '10mb',
-
- mime_types: [
- {title : "Image files", extensions : "jpg,gif,png"},
- {title : "Zip files", extensions : "zip"}
- ]
- },
- rename: true,
-
- sortable: true,
- dragdrop: true,
- views: {
- list: true,
- thumbs: true, // Show thumbs
- active: 'thumbs'
- },
- flash_swf_url : 'js/Moxie.swf',
- silverlight_xap_url : 'js/Moxie.xap'
- });
- $('#form').submit(function(e) {
- if ($('#uploader').plupload('getFiles').length > 0) {
- $('#uploader').on('complete', function() {
-
- $('#form')[0].submit();
- });
- $('#uploader').plupload('start');
- }
- });
- });
- </script>
- {/literal}
复制代码 6.upload.php见附件(放到admin目录下)
执行完上面几部可以看到如下的演示效果
7.后端代码的处理
当我们的图片上传成功后,还需要在数据库中保存信息,在product.php中做如下修改(添加和编辑一样的道理就不分别说明)
- //上传图片数量
- $uploader_count = $_POST['uploader_count'];
- //上传图片名称
- $files="";
- for($i = 0;$i<$uploader_count;$i++)
- {
- $name = "uploader_".$i."_name";
- //echo $_POST[$name];
- $files = $i==0?$_POST[$name]:$files.",".$_POST[$name];
- }
复制代码 这样在数据库中生成的字符串就是 1.jpg,2.jpg ....然后接下来你懂得,使用explode函数处理就可以取得图片信息,接下来需要插入到数据库中,在这里我建立了一个product_images的字段在product表中,修改后的sql语句如下:
- $sql = "INSERT INTO " . $dou->table('product') .
- " (id, cat_id, product_name, price, defined, content, product_image ,keywords, add_time, description,product_images)" .
- " VALUES (NULL, '$_POST[cat_id]', '$_POST[product_name]', '$_POST[price]', '$_POST[defined]', '$_POST[content]', '$file', '$_POST[keywords]', '$add_time', '$_POST[description]','$files')";
复制代码
二.图集列表
当我们在编辑商品的时候,为了方便我们在后台看到图集列表,在product.php 中改下update的代码:
- elseif ($rec == 'update') {
- if (empty($_POST['product_name']))
- $dou->dou_msg($_LANG['product_name'] . $_LANG['is_empty']);
- if (!$check->is_price($_POST['price'] = trim($_POST['price'])))
- $dou->dou_msg($_LANG['price_wrong']);
-
- // 上传图片生成
- if ($_FILES['product_image']['name'] != "") {
- // 分析商品图片名称
- $basename = basename($_POST['product_image']);
- $file_name = substr($basename, 0, strrpos($basename, '.'));
-
- $upfile = $img->upload_image('product_image', $file_name); // 上传的文件域
- $file = $images_dir . $upfile;
- $img->make_thumb($upfile, $_CFG['thumb_width'], $_CFG['thumb_height']);
-
- $up_file = ", product_image='$file'";
- }
-
- // CSRF防御令牌验证
- $firewall->check_token($_POST['token'], 'product_edit');
-
- // 格式化自定义参数
- $_POST['defined'] = str_replace("\r\n", ',', $_POST['defined']);
-
-
- //上传图片数量
- $uploader_count = $_POST['uploader_count'];
-
- //上传图片名称
- $files="";
- for($i = 0;$i<$uploader_count;$i++)
- {
- $name = "uploader_".$i."_name";
- //echo $_POST[$name];
- $files = $i==0?$_POST[$name]:$files.",".$_POST[$name];
- }
- if(empty($files)){
- $files = $_POST['product_images2'];
- }
-
- //echo $files;
- $sql = "update " . $dou->table('product') .
- " SET cat_id = '$_POST[cat_id]', product_name = '$_POST[product_name]', price = '$_POST[price]', defined = '$_POST[defined]' ,content = '$_POST[content]'" .
- $up_file . ", keywords = '$_POST[keywords]', description = '$_POST[description]',product_images = '$files' WHERE id = '$_POST[id]'";
- //echo $sql;
- $dou->query($sql);
-
- $dou->create_admin_log($_LANG['product_edit'] . ': ' . $_POST['product_name']);
- $dou->dou_msg($_LANG['product_edit_succes'], 'product.php');
- }
复制代码
前台HTML文件,product.htm需要增加(198行):
- <!-- 列表-->
- {if $product.product_images}
- <tr>
- <td>产品图集列表</td>
- <td>
- <!-- {foreach from=$product.product_images item='image'} -->
- <a href="../upload/{$image}" target="_blank" style="display:block;float:left; padding:5px;"><img src="../upload/{$image}" height="100"/>
- <span style="display:block;text-align:center;background:black;color:white">{$image}</span>
- </a>
- <!-- {/foreach} -->
- </td>
- <input type="hidden" name="product_images2" value ="{$product.product_images2}"/>
- </tr>
- {/if}
复制代码 此步骤完成,如果成功在编辑商品的时候会看到如下画面:
三.前台HTML显示
当我们完成上面这几部,并且数据都已经存在数据库中时,我们就可以编写我们的前台的product.dwt来显示我们的商品信息
步骤如下:
product.php 28行 增加如下代码:
- //图集列表
- if($product['product_images'])
- {
- $picList = explode(',',$product['product_images']);
- if(count($picList)>0){
- $product['product_images'] = $picList;
- }
- }
复制代码
前台CSS,JS文件不再给出。网上有很多效果,完整做完的效果图就是这样拉
upload.php 源码:
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header(" ragma: no-cache");
@set_time_limit(5 * 60);
// Settings
$targetDir = '../upload';
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds
// Create target dir
if (!file_exists($targetDir)) {
@mkdir($targetDir);
}
// Get a file name
if (isset($_REQUEST["name"])) {
$fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
$fileName = $_FILES["file"]["name"];
} else {
$fileName = uniqid("file_");
}
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
// Remove old temp files
if ($cleanupTargetDir) {
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}.part") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
@unlink($tmpfilePath);
}
}
closedir($dir);
}
// Open temp file
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}
if (!empty($_FILES)) {
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
}
// Read binary input stream and append it to temp file
if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
} else {
if (!$in = @fopen("php://input", "rb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($out);
@fclose($in);
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}
// Return Success JSON-RPC response
die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
|