用H5的新功能属性:FileReader、FormData实现即时上传图片。 参考链接: http://blog.csdn.net/jackfrued/article/details/8967667 http://www.cnblogs.com/lhb25/p/html5-formdata-tutorials.html https://www.douban.com/note/33698
参考链接:
http://blog.csdn.net/jackfrued/article/details/8967667
http://www.cnblogs.com/lhb25/p/html5-formdata-tutorials.html
https://www.douban.com/note/336989176/
1. [代码][JavaScript]代码
html代码: <form id="imageForm" method="post" enctype="multipart/form-data"> <ol class="add_photo"> <li id="clickMyImg" onclick="$('#myImg').click();" class="disbox-center add_icon" style="position: relative; overflow: hidden; transform-origin: 0px 0px 0px;opacity: 1; transform: scale(1, 1);">+</li> </ol> <input type="file" accept="image/*" name="photo" id="myImg" style="display: none;"> </form> <ol class="showPhotos" ></ol> script代码: var showImg=function(data) { $(".showPhotos").append('<li><img src="' + data + '" /></li>'); } $('#myImg').live('change', function () { $("#clickMyImg").html('<img width="75px" height="75px" src="../images/wap2/loading.gif" />'); var oFile=this.files[0]; var oReader = new FileReader(); oReader.onload = function(e){ var sBase64 = e.target.result; // 部分Android下base64字符串格式不完整 if(window.gIsAndroid && sBase64.indexOf("data:image/") != 0){ var sMime = sName.split(".").pop().toLowerCase(); sBase64 = sBase64.replace("base64,", "image/" + sMime + ";base64,"); } showImg(sBase64); var oData = new FormData(document.getElementById("imageForm")); $.ajax({ type:'POST', url : serverUrl.domain+'user/uploadphoto', data: oData, dataType:'json', processData: false, contentType: false, success : function(data) { $("#clickMyImg").html('+'); messageShowHide(); }, error : function(data) { $('.message_tip').html('上传头像出错!'); messageShowHide(); } }); sBase64 = null; } oReader.readAsDataURL(oFile); });