PHP处理base64图片上传

场景描述

项目需要有个图片上传的功能,根据需求直接使用前端小哥写好的页面。上传图片部分
前端直接可以判断上传文件的大小,并且很友好的显示出选择的图片。PHP后台一般直接从$_FILE这个魔术变量里面获取上传文件信息,不过我在获取前端约定好的字段时,并没有读取到该字段的信息,这是为什么呢?

问题分析

先不看前端是怎么写的,直接选择一个图片,打开chrome检查元素,看关键部分:在src链接的是data:image/jpeg;base64,/...

猜前端小哥直接把原来的file转编成了base64的字符串。为什么是字符串?Google的结果得知,Base64是一组相似的二进制到文本(binary-to-text)的编码规则

实践

知道传过来的是字符串,那就可以直接通过对应字段获取,最后把它转存起来,变成图片。

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
public function getUpdateFile($fileKey, $isBase64)
{
// 允许上传的文件
$allowFile = ['image/jpeg', 'image/jpg', 'image/png'];
if ($isBase64) {
$fileType = substr(strstr(strstr($fileKey, ';', true), ':'), 1);
$fileBody = substr(strstr($fileKey, ','), 1);
$data = base64_decode($fileBody);
} else {
// 被上传的文件名
$fileType = $_FILES[$fileKey]['type'];
$fileSize = $_FILES[$fileKey]['size'];
$fileTmpName = $_FILES[$fileKey]['tmp_name'];
$fileError = $_FILES[$fileKey]['error'];
// 2M以上
if ($fileSize > 2097152 and $fileSize < 102400) {
self::returnAjax(self::STATUS_ERROR, '请将上传文件控制在2M以及100kb之间!');
}
// 上传失败
if ($fileError > 0) {
self::returnAjax(self::STATUS_ERROR, '网络请求失败!');
}
}
// 文件格式不允许
if (!in_array($fileType, $allowFile)) {
self::returnAjax(self::STATUS_ERROR, '上传文件格式不正确!');
}
$basePath = APPLICATION_PATH . '/../public/upload/';
$tmp = explode('/', $fileType);
if ($tmp[1] === 'jpeg') {
$pType = 'jpg';
} else {
$pType = $tmp[1];
}
$fileName = date('Ymdhis') . '.' . $pType;
$dirData = date('Ymd');
if (!file_exists($basePath . $dirData)) {
mkdir($basePath . $dirData, 0777);
}
$savePath = $basePath . $dirData . '/' . $fileName;
if ($isBase64) {
file_put_contents($savePath, $data);
} else {
move_uploaded_file($fileTmpName, $savePath);
}
return $savePath;
}

坚持原创技术分享,您的支持将是鼓励我继续创作的动力!