圖片上傳前端實現
阿新 • • 發佈:2017-11-13
multipart splice ons chang console resp 前端 返回 res
基於bootstrap實現圖片上傳,具體代碼實現如下
<form id="poster_form" class="form-horizontal" method="post" enctype=‘multipart/form-data‘> <div class="control-group"> <label class="control-label" >圖片上傳*</label> <div class="controls"> <div class="input-group"> <input id="img-name-box" name=‘poster_path‘ type="text" class="form-control" value="" readonly> <span class="input-group-btn"> <button id="up-btn" class="btn btn-success" type="button">選擇文件</button> </span> </div> </div> </div> </form> <form id="imgForm" action="/phptext/php/5-img.php" method="post" enctype="multipart/form-data" target="file_upload_return"> <input id="up-file" name="up_img" type="file" style="display: none" value="" /> </form> <iframe id="file_upload_return" hidden="true" name="file_upload_return"></iframe> <div class="img-box"> <img src="" id="img-show" class="img-responsive" hidden="hidden" > </div>
js代碼實現如下:
$(function () { $("#up-btn").on(‘click‘,function(){ $("#up-file").click(); }); //抓取選擇文件事件 $(‘#up-file‘).on(‘change‘, function(){ // var name = $(this)[0].files[0].name; var ext = this.value.toLowerCase().split(‘.‘).splice(-1); if ( ext == ‘png‘ || ext == ‘jpg‘) { console.log(1111); $(‘#imgForm‘).submit(); } else { alert(‘只能上傳jpg、png格式的圖片‘); } }); //submit返回 $("#file_upload_return").load(function(){ var body = $(window.frames[‘file_upload_return‘].document.body); var result = eval(‘(‘ + body[0].textContent + ‘)‘); console.log(result); if (result) { $(‘#img-name-box‘).val(result.path); $(‘#img-show‘).attr(‘src‘, ‘http://localhost/phptext/YinLogs/Html/‘ + result.path).show(); } else { alert(result.info); } }); });
圖片上傳前端實現