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