标签:mobile patch over play pre log write com success
做一个前端可压缩并且上传图片到后台的功能
用到的主要是jq和LocalResizeIMG这2个库
a.引入脚本文件
<script type=‘text/javascript‘ src=‘js/jquery-2.0.3.min.js‘></script> <script type=‘text/javascript‘ src=‘js/LocalResizeIMG.js‘></script> <script type=‘text/javascript‘ src=‘js/patch/mobileBUGFix.mini.js‘></script>
b.编写html
<div style="width:100%;margin:10px auto; border:solid 1px #ddd; overflow:hidden; "> <input type="file" id="uploadphoto" name="uploadfile" value="请点击上传图片" style="display:none;" /> <div class="imglist"></div> <a href="javascript:void(0);" onclick="uploadphoto.click()" class="uploadbtn">点击上传文件</a> </div>
c.编写css
body{font-family:"微软雅黑"} *{margin: 0;padding: 0; } .uploadbtn{ display:block;height:40px; line-height:40px; color:#333; text-align:center; width:100%; background:#f2f2f2; text-decoration:none; } .imglist{min-height:200px;margin:10px;} .imglist img{width:100%;}
d.执行上传代码
<script type="text/javascript"> $(document).ready(function(e) { $(‘#uploadphoto‘).localResizeIMG({ //要压缩到的宽度 width: 1900, quality: 1, success: function (result) { // result.clearBase64是base64的数据 var submitData={ base64_string:result.clearBase64, }; $.ajax({ type: "POST", url: "upload.php", data: submitData, dataType:"json", success: function(data){ if (0 == data.status) { alert(data.content); return false; } else { alert(data.content); var attstr= ‘<img id=‘+‘element_id‘+‘ src="‘+data.url+‘">‘; $(".imglist").append(attstr); return false; } }, complete :function(XMLHttpRequest, textStatus){ }, error:function(XMLHttpRequest, textStatus, errorThrown){ //上传失败 alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); } }); } }); }); </script>
e.后端php接收数据并处理。
后端会接收前端的base64数据,并base64解码保存在images文件夹下面
<?php $base64_string = $_POST[‘base64_string‘]; $savename = uniqid().‘.jpeg‘;//localResizeIMG压缩后的图片都是jpeg格式 $savepath = ‘images/‘.$savename; $image = base64_to_img( $base64_string, $savepath ); if($image){ echo ‘{"status":1,"content":"图片上传成功,请用手指轻触要做为头像的区域","url":"‘.$image.‘"}‘; }else{ echo ‘{"status":0,"content":"上传失败"}‘; } function base64_to_img( $base64_string, $output_file ) { $ifp = fopen( $output_file, "wb" ); fwrite( $ifp, base64_decode( $base64_string) ); fclose( $ifp ); return( $output_file ); } ?>
思路就是前端把图片base64编码,再传到后台进行base64解码并保存把图片返回给客户端并在服务端保存一份。(需在服务器下运行代码)
参考资料:http://www.cnblogs.com/manongxiaobing/p/4720568.html
标签:mobile patch over play pre log write com success
原文地址:http://www.cnblogs.com/norm/p/6188318.html