Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法。可查看RFC2045~RFC2049,上面有MIME的详细规范。
Base64编码是从二进制到字符的过程,可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,就采用了Base64来将一个较长的唯一标识符(一般为128-bit的UUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数。在其他应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式。此时,采用Base64编码具有不可读性,需要解码后才能阅读。
首先定义一个方法:
|
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
|
function uploadOne($file)
{ header('Content-type:text/html;charset=utf-8');
$base64_image_content = trim($file);
//正则匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
$type = $result[2];//图片后缀
$dateFile = date('Y-m-d', time()) . "/"; //创建目录
$new_file = UPLOAD_BASE_PATH . $dateFile;
if (!file_exists($new_file)) {
//检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($new_file, 0700);
}
$filename = time() . '_' . uniqid() . ".{$type}"; //文件名
$new_file = $new_file . $filename;
//写入操作
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
return $dateFile . $filename; //返回文件名及路径
} else {
return false;
}
}
} |