apicp.UploadHeadImg.php
1.62 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
<?php
/**
* 跨域处理
*/
header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Methods:GET,POST");
/**
* 用户上传头像
*/
include "Common/JsonResponse.php";
include "Common/mysqlHelper.php";
include "Common/WechatHelper.php";
include "Common/Encrypter.php";
// id,头像
if (!isset($_POST['id']) || !isset($_POST['mediaId'])) {
JsonResponse::error('传参错误');
}
// 姓名唯一
$id = $_POST['id'];
$mysql = new mysqlHelper();
$data = $mysql->fetch("SELECT id FROM user WHERE id = ?", [$id]);
if (!isset($data)) {
JsonResponse::error('用户不存在');
}
// 获取头像数据,从微信临时素材图片中。
$wechat = new WechatHelper();
$img = $wechat->getMedia($_POST['mediaId']);
// 保存图片
$filename = time() . rand(1000, 9999) . ".jpg";
$tarfilename = "/upload/" . $filename;
$dir = str_replace('\\', '/', realpath(dirname(__FILE__) . '/'));
$dir = rtrim($dir, '/party/phpapi/');
$fp = fopen($dir . $tarfilename, "w");
fwrite($fp, $img);
fclose($fp);
// 组装用户需要的数据
$headimg = 'http://' . $_SERVER['SERVER_NAME'] . $tarfilename;
$time = time();
// pdo保存数据
$updateSql = "UPDATE user SET headimg = '{$headimg}', created = {$time} WHERE id = {$id};";
$rowCount = $mysql->update($updateSql);
if ($rowCount) {
JsonResponse::result([
'headimg' => $headimg
]);
} else {
JsonResponse::error('头像上传失败');
}