<h1>採用iframe上傳文件</h1> <form action="/xinwen/uploadfile/" enctype="multipart/form-data" target="ifr" method="post"> <iframe name="ifr" id="ifr"></iframe> <input type="file" name="fafa"><input type="submit" value="提交" onclick="iframeclick();"> </form>ajax
function iframeclick() { $('#ifr').load(function (){ var txt=$('#ifr').contents().find('body').text(); var obj=JSON.parse(txt) console.log(obj); }); }
<script> function changeup() { $('#ifr').load(function (){ var txt=$('#ifr').contents().find('body').text(); var obj=JSON.parse(txt); $('#prev').empty(); var imgtag=document.createElement('img'); imgtag.src='/'+obj.data; $('#prev').append(imgtag) console.log(obj); }); $('#fm1').submit(); } function submitClick() { var file_obj = document.getElementById('fafa').files[0]; var fd=new FormData(); fd.append('fafa',file_obj); $.ajax({ url: '/xinwen/uploadfile/', type:'POST', data:fd, processData:false, contentType:false, success:function (arg,a2,a3) { console.log(arg) console.log(a2) console.log(a3) }, } ); {# var xhr =new XMLHttpRequest();#} {# xhr.open('POST','/xinwen/uploadfile/',true);#} {#/*xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8');*/#} {#xhr.send(fd);#} {##} {#xhr.onreadystatechange=function () {#} {# if(xhr.readyState==4){#} {# console.log(xhr.responseText);#} {# }#} } function iframeclick() { $('#ifr').load(function (){ var txt=$('#ifr').contents().find('body').text(); var obj=JSON.parse(txt); $('#prev').empty(); var imgtag=document.createElement('img'); imgtag.src='/'+obj.data; $('#prev').append(imgtag) console.log(obj); }); } </script>app