UploadController.php
12.2 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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\user\controller;
use cmf\controller\RestUserBaseController;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Cache;
use think\Controller;
use think\Db;
use think\Validate;
/**
* @title 文件上传
* @description 文件上传
* @package api\wxapp\controller
*/
class UploadController extends RestUserBaseController
{
/**
* @title 上传单个文件
* @description 上传单个文件
* @author Tiger Yang
* @url /user/upload/one
* @method POST
*
* @header name:XX-Token require:1 default: desc:登录标识
* @header name:XX-Device-Type require:0 default:wxapp desc:设备类型
*
* @param name:file type:file require:1 other: desc:上传文件
*/
public function one()
{
$file = $this->request->file('file');
// 移动到框架应用根目录/public/upload/ 目录下
$info = $file->validate([
/*'size' => 15678,*/
'ext' => 'jpg,png,gif'
]);
$fileMd5 = $info->md5();
$fileSha1 = $info->sha1();
$findFile = Db::name("asset")->where('file_md5', $fileMd5)->where('file_sha1', $fileSha1)->find();
if (!empty($findFile)) {
$this->success("上传成功!", ['url' => cmf_get_asset_url($findFile['file_path']), 'filename' => $findFile['filename']]);
}
$info = $info->move(ROOT_PATH . 'public' . DS . 'upload');
if ($info) {
$saveName = $info->getSaveName();
$originalName = $info->getInfo('name');//name,type,size
$fileSize = $info->getInfo('size');
$suffix = $info->getExtension();
$fileKey = $fileMd5 . md5($fileSha1);
$userId = $this->getUserId();
Db::name('asset')->insert([
'user_id' => $userId,
'file_key' => $fileKey,
'filename' => $originalName,
'file_size' => $fileSize,
'file_path' => cmf_get_asset_url($saveName),
'file_md5' => $fileMd5,
'file_sha1' => $fileSha1,
'create_time' => time(),
'suffix' => $suffix
]);
$storage = cmf_get_option('storage');
if (isset($storage['type'])&&$storage['type']=='Qiniu') {
$this->uploadToQiniu($saveName);
}
$this->success("上传成功!", ['url' => cmf_get_asset_url($saveName), 'filename' => $originalName]);
} else {
// 上传失败获取错误信息
$this->error($file->getError());
}
}
/**
* 上传到七牛云
* @param $save_name
* @param bool $is_del_local
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function uploadToQiniu($save_name,$is_del_local=true){
$plugin=Db::name('plugin')->field('config')->where(['name'=>'Qiniu'])->find();
$config=json_decode($plugin['config'],true);
$filePath = './../upload/'.$save_name;
// 上传到七牛后保存的文件名
$key =$save_name;
require_once VENDOR_PATH . 'qiniu/php-sdk/autoload.php';
// 需要填写你的 Access Key 和 Secret Key
$accessKey = $config['accessKey'];
$secretKey = $config['secretKey'];
// 构建鉴权对象
$auth = new Auth($accessKey,$secretKey);
// 要上传的空间
$bucket = $config['bucket'];
$token = $auth->uploadToken($bucket);
// 初始化 UploadManager 对象并进行文件的上传
$uploadMgr = new UploadManager();
// 调用 UploadManager 的 putFile 方法进行文件的上传
list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
if($is_del_local){
unlink($filePath);
}
if ($err !== null) {
return ["err"=>1,"msg"=>$err,"data"=>""];
} else {
return ["err"=>0,"msg"=>"上传完成","data"=>cmf_get_image_url($ret['key'])];
}
}
public function test() {
return $this->uploadToQiniu('/15554568336598.png');
}
public function getToken() {
$appid = config('appId');
$secret = config('appSecret');
if (Cache::get('access_token')) {
return Cache::get('access_token');
}
$result = $this->curl_request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret);
$data = json_decode($result,true);
Cache::set('access_token',$data['access_token'],7000);
return $data['access_token'];
}
/**
* @title 获取海报图片地址
* @description 获取海报图片地址
* @url /user/upload/getPoster
* @method POST
*
* @header name:XX-Token require:1 default: desc:登录标识
* @header name:XX-Device-Type require:0 default:wxapp desc:设备类型
* @param name:card_id require:1 default:1 desc:分享名片id
*
* @return img_url: type:file require:1 other: desc:图片地址。前面需要拼接域名
*/
public function getPoster() {
$validate = new Validate([
'card_id' => 'require',
]);
$validate->message([
'card_id.require' => '缺少参数card_id!',
]);
$data = $this->request->param();
if (!$validate->check($data)) {
$this->error(['code'=>'40003','msg'=>$validate->getError()]);
}
//通过名片id 获取名片信息
$info = Db::name('card')
->alias('c')
->join('user u','c.user_id = u.id','left')
->where(['c.id' => $data['card_id']])
->field('c.name,c.position,c.company,c.tel,c.email,u.avatar')
->find();
$token = $this->getToken();
$url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$token;
$arr = [
'scene' => $data['card_id'].','.$this->userId
];
//生成图片
$xmlstr = $this->curl_request($url,json_encode($arr));
header("content-type: image/png");//如果要看报什么错,可以先注释调这个header
$nickname = $info['name'];//姓名
$position = $info['position'];//职称
$company = $info['company'];//公司
$tel = $info['tel'];//电话
$email = $info['email'];//邮箱
$tishi = '长按保存二维码';//提示
$logourl = file_get_contents($info['avatar']);//微信头像
$beijing = ROOT_PATH . 'public' . DS . 'upload/beijing.png';//海报最底层得背景
//$youxiang = ROOT_PATH . 'public' . DS . 'upload/youxiang.png';//海报最底层得背景
//$dianhua = ROOT_PATH . 'public' . DS . 'upload/dianhua.png';//海报最底层得背景
//$youxiang = imagecreatefrompng($youxiang);
//$dianhua = imagecreatefrompng($dianhua);
$beijing = imagecreatefrompng($beijing);
$logourl = imagecreatefromstring($logourl);
$logourlfx = imagesx($logourl); // 获取宽度
$logourlfy = imagesy($logourl); // 获取高度
//3.使用固定的公式计算新的宽高
$logourlsx = 300;
$logourlsy = 300;
//4.生成目标图像资源 微信头像
$logourl_small = imagecreatetruecolor($logourlsx,$logourlsy);
$color1 = imagecolorallocate($logourl_small, 255, 255, 255);
imagefill($logourl_small, 0, 0, $color1);
imageColorTransparent($logourl_small, $color1);
//5.进行缩放
imagecopyresampled($logourl_small,$logourl,0,0,0,0,$logourlsx,$logourlsy,$logourlfx,$logourlfy);
$erweimaurl = imagecreatefromstring($xmlstr);
$image_3 = imageCreatetruecolor(imagesx($beijing),imagesy($beijing));
$color2 = imagecolorallocate($image_3, 255, 120, 43);
imagefill($image_3, 0, 0, $color2);
imageColorTransparent($image_3, $color2);
imagecopyresampled($image_3,$beijing,0,0,0,0,imagesx($beijing),imagesy($beijing),imagesx($beijing),imagesy($beijing));
//字体颜色
$white = imagecolorallocate($image_3, 255, 255, 255);
$rqys = imagecolorallocate($image_3, 255, 255, 255);
$black = imagecolorallocate($image_3,255,255,255);
$font = ROOT_PATH . 'public'."/static/font-awesome/fonts/simkai.ttf"; //写的文字用到的字体。字体最好用系统有得,否则会包charmap的错,这是黑体
//imagettftext设置生成图片的文本
//imagettftext($image_3,35,0,100,920,$black,$font,$nickname);//姓名
//imagettftext($image_3,26,0,300,920,$black,$font,$position);//职称
//imagettftext($image_3,26,0,100,980,$black,$font,$company);//公司
//imagettftext($image_3,26,0,100,1040,$black,$font,$tel);//电话
//imagettftext($image_3,26,0,100,1100,$black,$font,$email);//邮箱
//imagettftext($image_3,26,0,440,1170,$black,$font,$tishi);//提示
//imagecopymerge($image_3,$logourl_small, 240,250,0,0,$logourlsx,$logourlsy,100);//左,上,右,下,宽度,高度,透明度
//imagecopymerge($image_3,$youxiang, 50,350,0,0,imagesx($youxiang),imagesy($youxiang),100);//左,上,右,下,宽度,高度,透明度
//imagecopymerge($image_3,$dianhua, 50,390,0,0,imagesx($dianhua),imagesy($dianhua),100);//左,上,右,下,宽度,高度,透明度
//imagecopymerge($image_3,$erweimaurl, 120,100,0,0,imagesx($erweimaurl),imagesy($erweimaurl), 100);
//2.获得源文件的宽高
$fx = imagesx($erweimaurl); // 获取宽度
$fy = imagesy($erweimaurl); // 获取高度
//3.使用固定的公式计算新的宽高
$sx = $fx/1.8;
$sy = $fy/1.8;
//4.生成目标图像资源 小程序码
$small = imagecreatetruecolor($sx,$sy);
$color3 = imagecolorallocate($small, 255, 120, 43);
imagefill($small, 0, 0, $color3);
imageColorTransparent($small, $color3);
//5.进行缩放
imagecopyresampled($small,$erweimaurl,0,0,0,0,$sx,$sy,$fx,$fy);
//imagecopymerge($image_3,$small, 450,875,0,0,imagesx($small),imagesy($small), 100);
//生成图片
$name = time().rand(1000,9999);
imagepng($image_3,ROOT_PATH . 'public' . DS . 'upload/'.$name.'.png');//在浏览器上显示
imagedestroy($image_3);
$res['img_url'] = 'https://jnlexin.com/upload/'.$name.'.png';
$this->success('获取成功',$res);
}
//参数1:访问的URL,参数2:post数据(不填则为GET),参数3:提交的$cookies,参数4:是否返回$cookies
public function curl_request($url,$post='',$cookie='', $returnCookie=0){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
if($post) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
if($cookie) {
curl_setopt($curl, CURLOPT_COOKIE, $cookie);
}
curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
if (curl_errno($curl)) {
return curl_error($curl);
}
curl_close($curl);
if($returnCookie){
list($header, $body) = explode("\r\n\r\n", $data, 2);
preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
$info['cookie'] = substr($matches[1][0], 1);
$info['content'] = $body;
return $info;
}else{
return $data;
}
}
}