服务器之家

服务器之家 > 正文

thinkphp5 框架结合plupload实现图片批量上传功能示例

时间:2020-06-02 13:32     来源/作者:tang05709

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

在extend目录下新增目录uploader,并新建类Uploads

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
namespace uploader;
 
class Uploads {
 public static function upfile($file, $path = 'images', $add_domain = false) {
  $res = ['errno' => 1, 'errmsg' => '上传图片错误'];
  $data = '';
  if(!empty($file)) {
   // 上传根目录
   $file_path = 'uploads/';
   // 如果传了路径过来,则加入路径
   if(!empty($path)) {
    $file_path .= $path .'/';
   }
   if (!file_exists($file_path)) {
    @mkdir($file_path);
   }
   // 上传
   $info = $file->move($file_path);
   // 获取后缀
   $ext = strtolower($info->getExtension());
   //判断后缀是否合法
   $exts = ['jpg', 'png', 'gif', 'jpeg', 'mp4', 'avi', '3gp'];
   if(in_array($ext, $exts)) {
    $save_name = $info->getSaveName();
    $save_path = "/" . $file_path . $save_name;
    if($add_domain) {
     $save_path = "http://www.localhost.com/" . $file_path . $save_name;
    }
    $res = ['errno' => 0, 'data' => $save_path];
   } else {
    $res = ['errno' => 1, 'errmsg' => $ext];
   }
  } else {
   $res = ['errno' => 1, 'errmsg' => '请选择图片!'];
  }
  
  return $res;
 }
}
?>

使用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
 
namespace app\backend\controller;
 
use think\Controller;
use think\Request;
use uploader\Uploads;
 
class Upload extends Controller
{
 public function upload(Request $request) {
  $files = $request->file("file");
  $updir = $request->post('updir');
  $res = Uploads::upfile($files, $updir);
  return json_encode($res);
 }
 
 public function del_upload(Request $request) {
  $res = ['errno' => 1, 'errmsg' => '删除失败'];
  $filename = $request->post('filename');
  if(!empty($filename)) {
   @unlink($_SERVER['DOCUMENT_ROOT'] . $filename);
   $res = ['errno' => 0, 'errmsg' => $filename];
  }
  return json_encode($res);
 }
 
}
 
?>

前端js

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
var image_files = new Array(); // 多图片上传临时保存
$(document).ready(function() {
 $('.media-picker').each(function() {
  var el = $(this);
  var elbtn = el.find('.media-picker-button');
  var multi_selection = false;
  var inputField = el.find('input[type=hidden]');
  // 是否多文件上传
  if(elbtn.attr('data-multiple') == 'multiple') {
   multi_selection = true;
  }
  // 上传目录
  var upload_path = inputField.attr('upload-path');
  var uploader = new plupload.Uploader({
   runtimes : 'html5,flash,silverlight,html4',
   browse_button : elbtn.attr('data-id') + '_uploader',
   multi_selection: multi_selection,
   auto_start: true,
   flash_swf_url : '../plugins/plupload/js/Moxie.swf',
   silverlight_xap_url : '../plugins/plupload/js/Moxie.xap',
   url : '/backend/upload',
   
   filters: {
    mime_types : [ //只允许上传图片和zip,rar文件
    { title : "Image files", extensions : "jpg,jpeg,gif,png,bmp" },
    { title : "Video files", extensions : "mp4,3gp" }
    ],
    max_file_size : '10mb', //最大只能上传10mb的文件
    prevent_duplicates : false //不允许选取重复文件
   },
 
   init: {
    PostInit: function() {},
 
    BeforeUpload: function(up, file) {
     up.setOption('multipart_params', {'updir': upload_path})
    },
 
    FilesAdded: function(up) {
     up.start(); //选择完后直接上传
    },
 
    FileUploaded: function(up, file, info) {
     if (info.status == 200)
     {
      var file_type = file.type;
      var is_image = file_type.indexOf('image');
      var is_video = file_type.indexOf('video');
      // 解析返回的数据
      var result = JSON.parse(info.response);
      var img_list = "";
      if(result.errno == 0) {
       // 返回的图片上传结果
       var file_name = result.data;
       if(multi_selection) {
        // 多图片上传不考虑视频
        if (is_image > -1) {
         // 存入临时数组
         image_files.push(file_name);
         inputField.val(JSON.stringify(image_files));
         for (var i = 0; i < image_files.length; i++) {
          img_list += "<li><img src='"+image_files[i]+"' /><span class='delete-image'>✖</span><p>"+image_files[i]+"</p></li>";
         }
        }
       } else {
        inputField.val(file_name);
        if (is_image > -1) {
         img_list = "<li><img src='"+result.data+"' /><span class='delete-image'>✖</span><p>"+result.data+"</p></li>";
        }
        if (is_video > -1) {
         img_list = "<li><video controls src='"+result.data+"'></video><span class='delete-image'>✖</span><p>"+result.data+"<p></li>";
        }
       }
       el.find('.image-list').html(img_list);
      } else {
       alert(result.errmsg);
      }
     }
     else
     {
      alter(info.response);
     }
    },
 
    Error: function(up, err) {
     alert(err.response);
    }
   }
  })
  uploader.init();
 
 
  // 删除
  if (multi_selection) {
   el.on('click', '.delete-image', function() {
    var file_name = inputField.val();
    var elDel = $(this);
    // 得到filename
    var current_file_name = elDel.next('p').html();
    // 删除当前的父级li
    elDel.parent().remove();
    // 重新赋值数组
    var new_image_files = new Array();
    if (image_files != '') {
     new_image_files = image_files;
    } else {
     new_image_files = $.parseJSON(file_name);
    }
    // 去掉数组中的当前值
    for(var i in new_image_files) {
     if(new_image_files[i] == current_file_name) {
      new_image_files.splice(i,1);
      break;
     }
    }
    $.ajax({
      type: "POST",
      url: "/backend/del_upload",
      data: "filename=" + current_file_name,
      success: function(msg) {
        console.log(msg)
      }
    });
    inputField.val(JSON.stringify(new_image_files));
   });
  } else {
   el.on('click', '.delete-image', function(){
    // 显示值为空
    var file_name = inputField.val();
    el.find('.image-list').html('');
    inputField.val('');
    $.ajax({
     type: "POST",
     url: "/backend/del_upload",
     data: "filename=" + file_name,
     success: function(msg) {
       console.log(msg)
     }
    });
   });
  }
 })
})

希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。

原文链接:https://blog.csdn.net/tang05709/article/details/85261152

相关文章

热门资讯

歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
超A是什么意思 你好a表达的是什么
超A是什么意思 你好a表达的是什么 2019-06-06
返回顶部