AttachmentModel.class.php
2.8 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
<?php
namespace Common\Model;
/**
* 素材附件模型类
*/
class AttachmentModel extends AbstractModel
{
const UPLOAD_IMAGE_SIZE = 20000000;
private $upload_dir = '../../trunk/Message/attachment/';
// 素材入库
public function add()
{
$bool = false;
$attachment = $this->initAttac();
if(is_array($attachment) && $attachment){
$bool = $this->_m->insert_all($attachment);
}
return boolval($bool);
}
/**
* 整理素材入库数据
* @author <362431947@qq.com>
* @date 2018-10-09
* @return array
*/
private function initAttac()
{
$attachment = [];
$index = 0;
foreach ($_FILES as $key => $file) {
$attachment[$index]['path'] = $this->upload($file);
$attachment[$index]['domain'] = md5($_SERVER['HTTP_HOST']);
$attachment[$index]['created'] = $this->microtime();
$index++;
}
return $attachment;
}
/**
* 素材附件上传
* @author <362431947@qq.com>
* @date 2018-10-09
* @param array $file
* @param string $subdir
* @return mixed
*/
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;
}
}