前台
<style> .file { position: relative; display: inline-block; border: 1px solid #333; padding: 4px 10px; overflow: hidden; text-decoration: none; text-indent: 0; line-height: 15px; border-radius: 5px; color: #000; background:#ccc; /* 一些不支持背景渐变的浏览器 */ background:-moz-linear-gradient(top, #fff, #ccc); background:-webkit-gradient(linear, 0 0, 0 bottom, from(#fff), to(#ccc)); background:-o-linear-gradient(top, #fff, #ccc); } .file input { position: absolute; font-size: 50px; right: 0; top: 0; opacity: 0; filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0); } </style>
<div id="image{$k}" class="btn-control"> 图片上传: <input type="file" id="bgyxun[{$k}]" οnclick='test(this)' class="image_bgy" placeholder="图片" value="" style="display:inline;"> <input type="hidden" name="img[{$k}][]" class="form-control" placeholder=""> </div> <span class="add-more glyphicon glyphicon-plus"></span>
<script type="text/javascript" src="__STATIC__/js/upload_file.js"></script> <script type="text/javascript"> function test(element){ var id=element.id; $('input[type="file"]').on('change',function(e){ var _this = $(this); var uimg = e.target.files[0]; var reader = new FileReader(); reader.readAsDataURL(uimg); reader.onload = function(e){ var b64 = this.result; _this.prev().prev('img').attr('src',b64); $.post( "{:url('index/form/ajaximg')}", { b64:b64 }, function(res){ _this.next().val(res.re); } ); } }); } </script>
后台
public function ajaximg(){ $base64_img = trim(input('b64')); $up_dir = './uploads/form/';//存放在当前目录的upload文件夹下 if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){ $type = $result[2]; if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){ $new_file = $up_dir.date('YmdHis_').'.'.$type; if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){ $img_path = str_replace('../../..', '', $new_file); $img_path = str_replace('./uploads/', '', $img_path); return json(['re'=>$img_path]); }else{ return json(['re'=>'失败']); } }else{ //文件类型错误 return json(['re'=>'错误']); } }else{ //文件错误 return json(['re'=>'错误1']); } }