adgjlxxx 2016-12-23
<html> <head>
<script src="/js/jquery-2.0.3.min.js"></script> <script src="/js/jquery.ajaxform.js"></script>
</head> <body>
<form name="form" action="upload" method="POST" id="userForm" enctype="multipart/form-data"> <div class="wrap"> <div class="album-old"> <div class="upload-btn btn-old"><input type="file" name="file" accept="image/*" id="image1" capture="camera"></div> <div class="upload-img "></div> </div> <div class="submit" style="margin-top: 200px;">提交</div> </div> </form>
</body>
<script type="text/javascript"> $(function(){ // $(".submit").on( // "click",function() { // var fileObj = document.getElementById("image1").files[0]; // var formData = new FormData(); // // formData.append("file",fileObj); // var xhr = new XMLHttpRequest(); // // xhr.open("post","/Api/News/upload",true); // xhr.send(formData); // // xhr.onload = function(e){ // if (this.status == 200) { // window.alert(this.responseText); // } // } // }) $(".submit").on("click",function() { userBrowser(); }); }); function userBrowser(){ var browserName=navigator.userAgent.toLowerCase(); if(/msie/i.test(browserName) && !/opera/.test(browserName)){ $("#userForm").ajaxSubmit(function(data){alert(data.fileurl);}); return ; }else if(/firefox/i.test(browserName)){ $("#userForm").ajaxSubmit(function(data){alert(data.fileurl);}); return ; }else if(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName)){ $("#userForm").ajaxSubmit(function(data){alert(data.fileurl);}); return ; }else if(/opera/i.test(browserName)){ $("#userForm").ajaxSubmit(function(data){alert(data.fileurl);}); return ; }else if(/webkit/i.test(browserName) &&!(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName))){ $("#userForm").ajaxSubmit(function(data){alert(data.fileurl);}); return ; }else{ $("#userForm").ajaxSubmit(function(data){alert(data.fileurl);}); } } function test() { alert(navigator.userAgent.toLowerCase().indexOf("MSIE")); if(navigator.userAgent.indexOf("MSIE")>0) $("#userForm").ajaxSubmit(function(data){alert(data);}); else $("#userForm").ajaxForm(function(data){alert(data);}); }
</html> 注:FormData IE8兼容问题
在新项目中使用的是springboot编写的api,涉及到ajax跨域请求和传输文件的问题,在这里记录一下。<input type="button" onclick="test();" value="