public function base64_image_content($base64_image_content)
{
//匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
$type = $result[2];
$path = 'frontend/uploads/images'.'/'.date("Ymd",time()).'/';
if (!file_exists($path)){
//检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($path, 777);
}
$picname = md5(uniqid(mt_rand(),true));
$new_file = $path . $picname;
//保存图片
if (file_put_contents($new_file, base64_decode(str_replace($result[1],'',$base64_image_content)))) {
$url = $path . $picname;
//return $new_file;
} else {
return false;
}
} else {
return false;
}
}
html页面:
<html>
<header>
<style>
.tabs{width:1200px;height:auto;border: solid 1px blue;}
.tabs1{font-size: 20px; font-family: 宋体}
.tabs1 td img{width:80px;height:40px;}
.tabs2{font-size: 15px;font-family: 宋体}
.tabs2 td img{width:80px;height:40px;}
</style>
<header>
<body>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<table data-toggle="table" align="center" class="tabs">
<thead>
<tr>
<th>ID</th>
<th>父级ID</th>
<th>名称</th>
<th>名称说明</th>
<th>图片</th>
</tr>
</thead>
<tbody>
<td><input type="hidden" id="_csrf" value="<?php echo $csrf;?>" "></td>
<?php foreach($optinfo as $k=>$v){;?>
<tr class="tabs1">
<td><?php echo $v['id'];?></td>
<td><?php echo $v['parent_id'];?></td>
<td><?php echo $v['opt_name'];?></td>
<td><?php echo $v['detail_name'];?></td>
</tr>
<?php foreach($v['secondmeau'] as $k1=>$v1){;?>
<?php if($v['id']==$v1['parent_id'])?>
<tr class="tabs2">
<td><?php echo " ".$v1['id'];?></td>
<td><?php echo " ".$v1['parent_id'];?></td>
<td><?php echo " ".$v1['opt_name'];?></td>
<td><?php echo " ".$v1['detail_name'];?></td>
<td><img src="<?php echo $v1['pic_img'];?>" id="tabs_img<?php echo $v1['id'];?>"></td>
<input type="hidden" class="id2" value="<?php echo $v['id'];?>">
<td><input type="file" onchange="Uploadimg(this.files,<?php echo $v1['id'];?>)"></td>
</tr>
<?php };?>
<?php };?>
</tbody>
</table>
</body>
</html>
<script type="text/javascript">
var csrf = $("#_csrf").val();
function Uploadimg(f,id){
var imgdata ='';
var reader = new FileReader();
reader.readAsDataURL(f[0]);
reader.onload = function(e) {
$("#tabs_img"+id).attr("src",e.target.result);
imgdata = e.target.result;
ajaxupfromimg(csrf,id,imgdata);
}
}
/***
* 上传图片
*/
function ajaxupfromimg(csrf,id,imgdata){
if(csrf && id && imgdata){
$.post('upimg',{_csrf:csrf,id:id,base64:imgdata},function (result){
if(result.status==1){
//console.log(result)
alert(result.message);
}else{
console.log(result);
//alert(result.message);
}
});
}
return false;
}
</script>
本文介绍如何通过HTML页面结合CSS样式和jQuery库,利用Base64编码和AJAX技术实现实时上传并预览图片的功能。用户选择图片后,先将其转化为Base64字符串,然后通过AJAX发送到服务器进行处理。
7332

被折叠的 条评论
为什么被折叠?



