AttachmentModel.class.php
3.38 KB
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
<?php
namespace Common\Model;
/**
* 素材附件模型类
*/
class AttachmentModel extends AbstractModel
{
const UPLOAD_IMAGE_SIZE = 20000000;
private $upload_dir = '../../trunk/Message/attachment/';
/**
* 构造方法
* @author <362431947@qq.com>
* @date 2018-10-10
*/
public function __construct()
{
parent::__construct();
}
// 素材入库
public function add()
{
$attachment_id_arr = [];
$microtme = $this->microtime();
$domain = md5($_SERVER['HTTP_HOST']);
if($_FILES){
foreach ($_FILES as $key => $file) {
$attach_id = 0;
$attachment = [];
$attachment['path'] = $this->upload($file);
$attachment['domain'] = $domain;
$attachment['created'] = $microtme;
$attach_id = $this->_m->insert($attachment);
if($attach_id){
$attachment_id_arr[] = $attach_id;
}
else{
break;
}
}
if(! $attach_id){
E('保存失败');
return false;
}
}
return $attachment_id_arr ? implode(',',$attachment_id_arr) : '';
}
/**
* 附件删除
* User: <362431947@qq.com>
* @param string $attachment_id
* @return mixed
* Date: 2018-10-10 Time: 22:13
*/
public function del($attachment_id = '')
{
return $this->_m->delete($attachment_id);
}
/**
* 素材附件上传
* User: <362431947@qq.com>
* @param array $file
* @param string $subdir
* @return bool|string
* @throws \Think\Exception
* Date: 2018-10-9 Time: 22:14
*/
public function upload(array $file,$subdir='')
{
if($file['error'])
{
E('文件上传失败!');
return false;
}
$suffix = strrchr($file['name'],'.');
//获取文件后缀.从文件名最后一个点开始截取知道结束
if(! in_array($suffix,['.jeg','.jpeg','.png']))
{
E('上传文件类型错误(后缀)!');
}
if($file['size'] > self::UPLOAD_IMAGE_SIZE)
{
E('上传文件不能超过' . self::UPLOAD_IMAGE_SIZE/1000 . 'k');
}
$subdir = $subdir . date('Y/m/');
if(! is_dir($this->upload_dir . $subdir))
{
$this->mkDirs($this->upload_dir . $subdir);
if(! $this->mkDirs($this->upload_dir . $subdir)){
E("子目录创建失败");
}
}
$basename = uniqid('message',true) . $suffix;
//如果目录不存在,递归创建
if(move_uploaded_file($file['tmp_name'],$this->upload_dir . $subdir . $basename))
{
// echo $subdir . $basename;
return $subdir . $basename;
}
else{
E("文件移动失败");
}
}
/**
* 递归创建目录
* @author <362431947@qq.com>
* @date 2018-10-09
* @param string $dir
* @return bool
*/
private function mkDirs($dir = '')
{
if(!is_dir($dir)){
if(! $this->mkDirs(dirname($dir))){
return false;
}
if(!mkdir($dir,0777)){
return false;
}
}
return true;
}
}