<?php
header('Content-type:text/html;charset=utf-8');
//读取图片文件,转换成base64编码格式
$image_file = './face_21.png';
$image_info = getimagesize($image_file);
$base64_image_content = "data:{$image_info['mime']};base64," . chunk_split(base64_encode(file_get_contents($image_file))); //保存base64字符串为图片
//匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
$type = $result[2];
$new_file = "./test.{$type}";
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
echo '新文件保存成功:', $new_file;
} }
?> <img src="<?php echo $base64_image_content;?>" />

实例:

<html>
<head>
<meta charset="utf-8">
</head>
<body>
<img id="articleImg" width="180" height="100">
<input type="file" value="上传" id="articleImgBtn" />
<script type="text/javascript" src = 'jquery-1.6.2+fix-9521.js'></script>
<script type="text/javascript">
$('#articleImgBtn').change(function () {
run(this, function (data) {
uploadImage(data);
});
});
function run(input_file, get_data) {
/*input_file:文件按钮对象*/
/*get_data: 转换成功后执行的方法*/
if (typeof (FileReader) === 'undefined') {
alert("抱歉,你的浏览器不支持 FileReader,不能将图片转换为Base64,请使用现代浏览器操作!");
} else {
try {
/*图片转Base64 核心代码*/
var file = input_file.files[0];
//这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
if (!/image\/\w+/.test(file.type)) {
alert("请确保文件为图像类型");
return false;
}
var reader = new FileReader();
reader.onload = function () {
get_data(this.result);
}
reader.readAsDataURL(file);
} catch (e) {
alert('图片转Base64出错啦!' + e.toString())
}
}
}
function uploadImage(img) {
//判断是否有选择上传文件
var imgPath = $("#articleImgBtn").val();
if (imgPath == "") {
alert("请选择上传图片!");
return;
}
//判断上传文件的后缀名
var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
if (strExtension != 'jpg' && strExtension != 'gif'
&& strExtension != 'png' && strExtension != 'bmp') {
alert("请选择图片文件");
return;
}
$.ajax({
type: "POST",
url: 'signup.php?act=reg', //jsonp跨域,但不支持POST请求
// data: {file: img.substr(img.indexOf(',') + 1)}, //视情况将base64的前面字符串data:image/png;base64,删除
data: {file: img}, //视情况将base64的前面字符串data:image/png;base64,删除
cache: false,
success: function (data) {
var return_info = JSON.parse(data);
if (return_info.status) {
$("#articleImg").attr('src', return_info.path);
alert("上传成功");
} else {
alert(return_infoerr_info);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("上传失败,请检查网络后重试");
}
});
}
</script>
</body>
</html>
function upload_image($file_data){
$upload_result = array('status' => true, 'msg'=>'','err_info'=>'');
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $file_data, $result)) {
//处理base64字符串
$img_base64 = str_replace($result[1], '', $file_data);
$img_base64 = str_replace('=', '', $img_base64);
$source_img = base64_decode($img_base64);
//判断文件大小
$file_size =
//上传目录
$basedir = './img_test';
//后缀
$img_suffix = $result[2];//文件后缀
//文件名
// $filename = uniqid();//文件名
$filename = date('YmdHis',time());//文件名
//文件完整路径
$filepath = $basedir . "/" . $filename . "." . $img_suffix;
//目录若果不存在,则创建目录
if(!is_dir($basedir)){
mkdir($basedir);
chmod($basedir,0777);
}
//上传文件
try {
file_put_contents($filepath, $img_base64);
$filepath = substr($filepath, 1);
$upload_result = array('status' => true, 'msg'=>'上传成功','err_info'=>'','path'=>$filepath);
return $upload_result;
} catch (Exception $e) {
$upload_result = array('status' => false, 'msg'=>'上传失败','err_info'=>$e->getMessage());
return $upload_result;
}
// if (file_put_contents($filepath, base64_decode(str_replace($result[1], '', $file_data)))) {
// //$size = getimagesize($filepath);
// $filepath = substr($filepath, 1);
// //$arr['filepath'] = $filepath;
// //$arr['size'] = $size[3];
// return $filepath;
// }else{
// return false;
// }
}else{
$upload_result = array('status' => false, 'msg'=>'上传失败','err_info'=>'请携带base64字符串的前缀');
return $upload_result;
}
}
$res = upload_image($file_data);
echo json_encode($res);

php接收base64编码的文件内容并保存的更多相关文章

  1. base64编码的 文件 图片

    //图片 转为 base64编码的文本 private void button1_Click(object sender, EventArgs e) { OpenFileDialog dlg = ne ...

  2. android逐行读取文件内容以及保存为文件

    用于长时间使用的apk,并且有规律性的数据 1,逐行读取文件内容 //首先定义一个数据类型,用于保存读取文件的内容 class WeightRecord { String timestamp; flo ...

  3. c++读取文件内容并保存到二维数组

    每行数据最后需要Tab处理 #include <iostream> #include <fstream> #include <string> using names ...

  4. ios开发Base64编码以及加密相关学习

    一:.Base64补充 ```objc 1.Base64简单说明 描述:Base64可以成为密码学的基石,非常重要. 特点:可以将任意的二进制数据进行Base64编码 结果:所有的数据都能被编码为并只 ...

  5. 在 Java 中如何进行 BASE64 编码和解码

    BASE64 编码是一种常用的字符编码,在很多地方都会用到.JDK 中提供了非常方便的 BASE64Encoder 和 BASE64Decoder,用它们可以非常方便的完成基于 BASE64 的编码和 ...

  6. 针对base64编码和URIEncode的一点研究

    Base64编码的作用 将任意的二进制比特串编码成由ASCii码中的64个可显示字符组成的字符串. 为什么需要base64编码? 所有的文件,本质上都是0.1组成的比特串,文本文件.二进制文件的区别只 ...

  7. Base64 编码

    Base64 字母表 Base64 编码将一个 8 位字节序列拆成 6 位的片段,并为每个 6 位的片段分配一个字符,这个字符是 Base64 字母表中的 64 个字符之一. Wert Zeichen ...

  8. Python Base64 编码

    0x00 Base64简介 0x01 常用场景举例 0x02 编.解码流程 0x03 Python中Base64编码与解码 0x00 Base64简介 我们知道在计算机中任何数据都是按ascii码存储 ...

  9. 关于图片的Base64编码

    什么是Base64编码 Base64编码是一种图片处理格式,通过特定的算法将图片编码成一长串字符串,在页面上显示的时候,可以用该字符串来代替图片的url属性. base64编码就是长得像下面这样子的代 ...

随机推荐

  1. oracle10g连接自动断开,报ORA-03135错误

    问题描述: oracle使用过一段时间,连接断开,报ORA-03135错误. 问题挖掘: 用pl/sql和sqlplus连接oracle,也存在该问题,确定该问题与连接方式无关. 查看服务器,发现没有 ...

  2. python json与字典对象互相转换

    改文章转自:https://www.cnblogs.com/Lin-Yi/p/7640147.html 1 import requests 2 import json 3 ''' 4 json.loa ...

  3. Vue.js图片预览插件

    vue-picture-preview-extend vue-picture-preview的扩展版本,本文中插件是由其他大神开发,我做了一些扩展,原文链接:https://segmentfault. ...

  4. POJ 2409 Let it Bead (Polya定理)

    题意 用k种颜色对n个珠子构成的环上色,旋转翻转后相同的只算一种,求不等价的着色方案数. 思路 Polya定理 X是对象集合{1, 2, --, n}, 设G是X上的置换群,用M种颜色染N种对象,则不 ...

  5. Unit Test Generator 简介

    从Visual Studio 2012开始,创建单元测试从右键菜单中消失了,这让开发者感觉很不习惯.其实创建单元测试并不是消失了,只是独立成一个扩展Unit Test Generator,单独安装这个 ...

  6. git一键提交修改文件

    git一键提交修改文件 首先安装git, 有git bash: 新建一个gitcmt文件,放置于与你的项目同级的目录里: 使用:打开git bash, 方法1. git pull\git status ...

  7. L206

    There are so many new books about dying that there are now special shelves set aside forthem in book ...

  8. 解决Eclipse中文乱码的问题

    注意:显示中文所有的编码方式主要是GBK和UTF-8,UTF-8是国际通用的中文编码标准,推荐使用. 一. 设置工作空间的编码 编辑器的编码会影响到所有的项目中的字符的显示,可以说是作用最为广泛的设置 ...

  9. js网页 唤醒支付宝

    过渡页: <script> window.location.href = 'alipays://platformapi/startApp?appId=10000011&url=al ...

  10. BZOJ3295: [Cqoi2011]动态逆序对(树状数组套主席树)

    3295: [Cqoi2011]动态逆序对 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 7465  Solved: 2662[Submit][Sta ...