本文实例讲述了thinkphp5框架整合plupload实现图片批量上传功能的方法。分享给大家供大家参考,具体如下:
在官网下载plupload http://http//www.plupload.com
或者点击此处本站下载。
这里我们使用的是pluploadqueue
在html页面引入相应的css和js,然后根据示例代码修改为自己的代码
<link rel="stylesheet" href="/assets/plupupload/css/jquery.plupload.queue.css" rel="external nofollow" type="text/css" media="screen" />
<div class="form-box-header"><h3>{:lang('photo')}</h3></div>
<div class="t-d-in-editor">
<div class="t-d-in-box">
<div id="uploader">
<p>{:lang('plupupload_tip')}</p>
</div>
<div id="uploaded"></div>
</div>
</div>
<script type="text/javascript" src="/assets/plupupload/plupload.full.min.js"></script>
<script type="text/javascript" src="/assets/plupupload/jquery.plupload.queue.js"></script>
<script type="text/javascript">
$(function() {
// setup html5 version
$("#uploader").pluploadqueue({
// general settings
runtimes : 'html5,flash,silverlight,html4',
url : '{:url("photo/upphoto")}',
chunk_size: '1mb',
rename : true,
dragdrop: true,
filters : {
// maximum file size
max_file_size : '10mb',
// specify what files to browse for
mime_types: [
{title : "image files", extensions : "jpg,gif,png"}
]
},
// resize images on clientside if we can
resize : {width : 320, height : 240, quality : 90},
flash_swf_url : '/assets/plupupload/moxie.swf',
silverlight_xap_url : '/assets/plupupload/moxie.xap',
init: {
postinit: function() {
$('#uploaded').html("");
},
fileuploaded : function(uploader , files, result) {
up_image = result.response;
if(up_image != ""){
$("#uploaded").append("<input type='hidden' name='images[]' value='"+up_image+"'/>"); //这里获取到上传结果
}
}
}
});
});
</script>
plupload整合:
<?php
/*
* 文件上传
*
* donald
* 2017-3-21
*/
namespace appbackendlogic;
use thinkmodel;
class plupupload extends model{
public function upload_pic($file_type="data"){
#!! important:
#!! this file is just an example, it doesn't incorporate any security checks and
#!! is not recommended to be used in production environment as it is. be sure to
#!! revise it and customize to your needs.
// make sure file is not cached (as it happens for example on ios devices)
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("pragma: no-cache");
/*
// support cors
header("access-control-allow-origin: *");
// other cors headers if any...
if ($_server['request_method'] == 'options') {
exit; // finish preflight cors requests here
}
*/
// 5 minutes execution time
@set_time_limit(5 * 60);
// uncomment this one to fake upload time
// usleep(5000);
// settings
//重新设置上传路径
$uploads = config('uploads_dir');
if(!empty($file_type)){
$uploads = $uploads .$file_type."/".date("ymd");
}
$targetdir = $uploads;
//$targetdir = 'uploads';
$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_");
}
//重命名文件
$filename_arr = explode(".", $filename);
$filename = myrule().".".$filename_arr[1]; //rule()请查看上篇我的上篇博客thinkphp同时上传多张图片文件重名问题
$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($filepath); //这里直接返回结果
// die('{"jsonrpc" : "2.0", "result" : "'.$filepath.'", "id" : "id"}');
}
}
最后controller或model获取结果并保存
$images = $request->post('images/a'); //这里一定要注意, thinkphp通过name获取post数组时会获取不到数据,需要在name后加/a,表示获取数组详见request的typecast
model('photoimage')->query_insert($images, $id);//批量插入图片
/**
* 强制类型转换
* @param string $data
* @param string $type
* @return mixed
*/
private function typecast(&$data, $type)
{
switch (strtolower($type)) {
// 数组
case 'a':
$data = (array) $data;
break;
// 数字
case 'd':
$data = (int) $data;
break;
// 浮点
case 'f':
$data = (float) $data;
break;
// 布尔
case 'b':
$data = (boolean) $data;
break;
// 字符串
case 's':
default:
if (is_scalar($data)) {
$data = (string) $data;
} else {
throw new invalidargumentexception('variable type error:' . gettype($data));
}
}
}
更多关于thinkphp相关内容感兴趣的读者可查看本站专题:《thinkphp入门教程》、《thinkphp模板操作技巧总结》、《thinkphp常用方法总结》、《codeigniter入门教程》、《ci(codeigniter)框架进阶教程》、《zend framework框架入门教程》及《php模板技术总结》。
希望本文所述对大家基于thinkphp框架的php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!