本文實例為大家分享了ajax上傳圖片到PHP并壓縮圖片顯示的具體代碼,供大家參考,具體內容如下
需求就是,上傳圖片并壓縮圖片頁面效果如下圖:
HTML代碼
<div id="main"> <div class="demo"> <div class="btn btn-success"> <span>上傳圖片</span> <input id="fileupload" type="file" name="mypic"> </div> <!--加載進度--> <div class="progress progress-striped"> <span class="progress-bar progress-bar-success bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style=""></span> <span class="percent">0%</span > </div> <!--顯示圖片--> <div id="showimg"></div> <!--刪除圖片--> <div class="files"></div> </div> </div>
CSS代碼和引入的bootstrap
<style type="text/css"> .demo{width:580px; margin:30px auto} .btn{position: relative;overflow: hidden;margin-right: 4px;} .btn input {position: absolute;top: 0; right: 0;margin: 0;border: solid transparent;opacity: 0;filter:alpha(opacity=0);} .progress { position:relative; margin-left:100px; margin-top:-24px; width:200px; border-radius:3px; display:none} .percent { position:absolute; top:1px; left:2%; color:#fff } .files{margin:10px 0} .delimg{margin-left:20px; color:#090; cursor:pointer;margin-top: -6px;} </style> <!--bootstrap.css3.3.7--> <link rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
JS代碼
<!--jquery1.8.1--> <script src="http://code.jquery.com/jquery-1.8.1.min.js"></script> <!--圖片jquery.form.js--> <script type="text/javascript" src="https://www.helloweba.net/demo/upload/jquery.form.js"></script> <script type="text/javascript"> $(function () { //進度條百分比加載顏色 var bar = $('.bar'); //進度條百分比 var percent = $('.percent'); //圖片顯示 var showimg = $('#showimg'); //進度條 var progress = $(".progress"); //新增 var files = $(".files"); var btn = $(".btn span"); $(".demo").wrap("<form id='myupload' action='action.php' method='post' enctype='multipart/form-data'></form>"); //點擊上傳圖片 $("#fileupload").change(function(){ //提交表單 $("#myupload").ajaxSubmit({ dataType: 'json', beforeSend: function() { //顯示進度條 progress.show(); //進度條為0 var percentVal = '0%'; bar.width(percentVal); percent.html(percentVal); btn.html("上傳中..."); }, //上傳進度 uploadProgress: function(event, position, total, percentComplete) { //進度條加載長度數據是number型 var percentVal = percentComplete + '%'; bar.width(percentVal) percent.html(percentVal); }, success: function(data) { //上傳成功返回參數 files.html("<b>"+data.name+"("+data.size+"k)</b> <span class='delimg btn btn-danger' rel='"+data.pic+"'>刪除</span>"); showimg.html("<img src='"+data.pic+"'>"); btn.html("上傳圖片"); }, error:function(xhr){ //上傳失敗 btn.html("上傳失敗"); bar.width('0') files.html(xhr.responseText); }, clearForm: true }); }); //刪除圖片js $(".delimg").live('click',function(){ //獲取圖片地址 var pic = $(this).attr("rel"); $.post("action.php?act=delimg",{imagename:pic},function(msg){ if(msg=='delete'){ files.html("刪除成功."); //刪除圖片效果 showimg.empty(); //隱藏進度條 progress.hide(); }else{ alert(msg); } }); }); }); </script>
新聞熱點
疑難解答
圖片精選