Home > Article > Backend Development > 手机压缩图片透过base64 上传 ajax不能post
手机压缩图片通过base64 上传 ajax不能post
<br /><br /><!DOCTYPE html><br /><html><br /><head><br /> <meta charset="utf-8"/><br /> <title>测试上传文件</title><br /> <script type="text/javascript" src="js/jquery.min.js"></script><br /> <script type="text/javascript" src="../js/mobileFix.mini.js"></script><br /> <script type="text/javascript" src="../js/exif.js"></script><br /> <script type="text/javascript" src="../js/lrz.js"></script><br /></head><br /><style> body {<br /> margin: 20px 20%;<br /> color: #777;<br /> text-align: center;<br />}</style><br /><body><br /><hr/><br /><input type="file" accept="image/*"/><br /><hr/><br /><script type="text/javascript"><br /> var input = document.querySelector('input');<br /> input.onchange = function () {<br /> lrz(this.files[0],<br /> {width: 800, height: 600,quality:0.5,<br /> before: function(){},<br /> fail: function(){},<br /> done: function (results) {<br /> // 你需要的数据都在这里,可以以字符串的形式传送base64给服务端转存为图片。<br /> var img = new Image();<br /> $('body').append(img);<br /> // 发送到后端<br /> var xhr = new XMLHttpRequest();<br /> var data = {<br /> base64: results.base64,<br /> size: results.base64.length // 校验用,防止未完整接收<br /> };<br /> xhr.open('POST', '1.php');<br /> xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');<br /> xhr.onreadystatechange = function () {<br /> if (xhr.readyState === 4 && xhr.status === 200) {<br /> var result = JSON.parse(xhr.response);<br /> result.error<br /> ? alert('服务端错误,未能保存图片')<br /> //: demo_report('服务端实存的图片', result.src, result.size);<br /> : img.src = result.src;<br /> }<br /> };<br /> xhr.send(JSON.stringify(data)); // 发送base64<br /><br /> },<br /> always: function(){<br /><br /> }<br /> }<br /> )};<br /><br /></script><br /></body><br /><br /></html><br /><br />
<br /><?php<br />$base64=file_get_contents("php://input"); //获取输入流<br />$base64=json_decode($base64,1);<br />$data = $base64['base64'];<br />preg_match("/data:image\/(.*);base64,/",$data,$res);<br />$ext = $res[1];<br />if(!in_array($ext,array("jpg","jpeg","png","gif"))){<br /> echo json_encode(array("error"=>1));die;<br />}<br />$file=time().'.'.$ext;<br />$data = preg_replace("/data:image\/(.*);base64,/","",$data);<br />if (file_put_contents('../uploadFiles/'.$file,base64_decode($data))===false) {<br /> echo json_encode(array("error"=>1));<br />}else{<br /> echo json_encode(array("error"=>0,'src'=>'../uploadFiles/'.$file));<br /><br />}<br /><br />