ThinkPHP5框架整合plupload实现图片批量上传

  本文实例讲述了thinkPHP5框架整合plupload实现图片批量上传功能的方法。分享给大家供大家参考,具体如下:

  在官网下载plupload https://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 app\backend\logic;
use think\Model;
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));
        }
    }
}

本站原创内容,如需转载请注明来源:https://www.liutonghui.com/152.html

上一篇 2017-12-05
下一篇 2018-03-07

评论列表(0条)

  • 暂时没有评论!

发表评论

captcha

相关推荐

  • 再谈PHP错误与异常处理

      请一定要注意,没有特殊说明:本例 PHP Version &lt; 7   说起PHP异常处理,大家首先会想到try-catch,那好,我们先看一段程序吧:有一个test.php文件,有一段简单的PHP程序,内容如下,然后命令行执行:php test.php &lt;?php $num = 0; try { echo 1/$num; } catch (Exception $e){ ......

    2017-06-12
    13780
  • 王杰出道35周年出新歌,60岁浪子仍洒脱

      12月17日,消失在歌迷视线中多年的老牌创作型歌手王杰突然发布了一首新歌《一场游戏一场梦(结束篇)》,今年是2022年,正好是王杰出道35年整。1987年12月19日,王杰在台湾发行首张专辑《一场游戏一场梦》正式出道,这张专辑一经发行就轰动了整个华语乐坛,在中国台湾、中国香港、中国大陆、东南亚等地都创下了惊人的销量,专辑中的同名主打歌《一场游戏一场梦》、《安妮》等歌曲直到今天依然是KTV点唱率非常高的歌曲。 点击上方播放视......

    2022-12-24
    8160
  • 远离谎话连篇三观不正的人

      人一辈子很短,应该活得光明磊落,问心无愧,才能对得起自己,让人生有价值有意义。做个坦坦荡荡堂堂正正的人是一辈子,做个谎话连篇自欺欺人的嘴炮也是一辈子。可偏偏就有这种人,不去付出行动创造幸福,反而把时间和精力都用在弄虚作假上,整天吹牛逼编故事表演给人看,三吹六哨,撒谎成性。一张破嘴吹天吹地撒谎尿屁的信口开河,嘴里没一句真话。天天活在谎言里,连一个真实的自己都不敢做,虚伪做作,三观不正。一边抱怨又一边虚度时光,诋毁别人的成就和拥有,把责......

    2023-01-19
    8564
  • 个人站长该何去何从!

      前些天有个同行和我说51nes易主了,而且是十万块贱卖的,听到后有些不解,一个十几年的老站难道就值十万吗?这与个人站长们的付出很不相符,绝大多数个人站长都是一无钱、二无人、三无资源的三无状态,一个人身兼美工、技术、编辑、SEO、市场营销等数职,十年如一日做站的艰辛只有自己才知道。   我不认识51nes,但一直关注着这个站,记得是好几年都没更新了,游戏也下不了,处于荒废的状态,很显然,站长转行了,也就无心打理,至于转行的原因要么是......

    2018-11-21
    26334
  • ThinkPHP文件上传类FileSystem自定义生成年月日目录

      FileSystem 是一个非常好用的文件上传扩展类,结合 Thinkphp 使用可以轻松的完成文件上传功能的开发。但是默认情况下 FileSystem 是按照&ldquo;年月日&rdquo;来生成上传日期目录的,长期使用下来就会有大量的&ldquo;Ymd&rdquo;目录,不方便管理,像我平时更新内容不多,如果以&ldquo;Ym&rdquo;的格式生成目录,按同一年同一月上传的文件放在一个日期目录中就方便管理多了。   需要......

    2023-04-23
    4502
  • 创业是条有趣的路,FC游戏网8周年

      能够创办一个网站,源源不断的为用户带来服务,是每个站长的梦想。2015年1月1日,也就是8年前的今天,我创办了FC游戏网,时间过得真的很快,一转眼已经过了8年。说起创办FC游戏网的初衷,其实是我自己喜欢玩游戏,能玩到那些各式各样的游戏,可以说是童年最快乐的时光,长大后对那些游戏依然念念不忘,因此,我就想一定有很多人像我一样,特别喜欢这些小时候玩的游戏,要是做一个网站把这些游戏收集整理起来,不光我自己玩着方便,也可以提供给别人下载,就......

    2023-01-01
    5000
  • PHP匿名函数使用技巧

      之前写过一篇闭包的使用(点击此处进入),这次深入汇总下php中匿名函数的深入用法和理解:   php中的匿名函数 也叫闭包函数 允许指定一个没有名称的函数。把匿名函数赋值给变量,通过变量来调用,举个简单的例子: &lt;?php $anonymousFunc = function($username){ echo $username; }; $anonymousFunc("乔峰!");   技巧1:&nbs......

    2018-11-15
    15450
  • JavaScrpit中异步请求Ajax实现,多个Ajax请求数据交互

      在前端页面开发的过程中,经常使用到Ajax请求,异步提交表单数据,或者异步刷新页面。   一般来说,使用Jquery中的ReferenceError: katex is not defined.post,$.getJSON,非常方便,但是有的时候,我们只需要ajax功能,这样引入Jquery比较不划算。   所以接下来便用原生JavaScrpit实现一个简单的Ajax请求,并说明ajax请求中的跨域访问问题,以及多个ajax请求的数......

    2017-07-19
    9500