/** * 以ajax方式上传一个图片 * @param evt <input type="file"/>的change事件 * @param targetElement 上传成功后会设置targetElement.value = file-url */ function uploadImage(evt, targetElement){ if ( typeof(FileReader) === 'undefined' ){ alert("您的浏览器不支持html5 文件上传。") return; } var files = evt.target.files; // FileList object var file = files[0]; var reader = new FileReader(); var m= reader.readAsDataURL(file); reader.onload = function(e){ var dataUrl = e.target.result; var base64 = dataUrl.split("base64,")[1]; var dataToPost ={ filename:file.name, fileAsBase64:base64 }; $.ajax({ url:"/file/uploadImage", data:dataToPost, dataType:"json", type:"POST", success:function(result){ if(result.code == "1"){ var data = result.data ||{}; if(targetElement){ targetElement.value = data.url; } }else{ alert(result.msg); } }, error:function(jqXHR, status, error){ alert("操作失败:" + error); } }); } }