前阵子工作中用到,贴上代码,仅保留上传有关的代码,发现 code 其实很少。
上传页面 html/js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| <head> <title></title> <script type="text/javascript"> function FinishUpload(filePath) { document.getElementById("uploadForm").reset(); if (!filePath) { alert("Import Failed!"); } else { alert("Imported Successfully to" + decodeURIComponent(filePath) + "!");
} }
function UploadFile() { var arr = document.getElementById("txtFile").value.split('.'); var fileType = arr[arr.length - 1]; if (fileType.toLowerCase().indexOf("csv") < 0) { document.getElementById("uploadForm").reset(); alert("Please select a csv file."); return false; }
document.getElementById("uploadForm").encoding = "multipart/form-data"; document.getElementById("uploadForm").submit(); }
function ResetFile(file) { var tmpForm = document.createElement('form'); file.parentNode.insertBefore(tmpForm, file); tmpForm.appendChild(file); tmpForm.reset(); tmpForm.removeNode(false); } </script> </head> <body> <form id="uploadForm" name="uploadForm" action="Upload.ashx" method="post" target="hidIframe" enctype="multipart/form-data"> <table cellpadding='0' cellspacing='0' style="width:100%;height:100%;border-collapse:collapse;" border="0" > <tr> <td> <input id="txtFile" name="txtFile" type="file" style="border:solid 1px Gray;" /> <iframe name="hidIframe" id="hidIframe" style="display:none;" ></iframe> </td> </tr>
<tr> <td> <input type="button" id="btnImportOK" value="Upload" onclick="UploadFile();" /> <input type="button" id="btnImportCancel" onclick="ResetFile(document.getElementById('txtFile'))" value="Reset"/> </td> </tr> </table> </form> </body> </html>
|
做到无刷新,基本原理就是:通过表单提交到 iframe 里,从而使刷新发生在 iframe 里。form 设置 action 指向处理上传的文件,target 指向 iframe。上传操作的结果可以返回到 iframe 里,调用父对象的 FinishUpload 方法显示是否上传成功。所以在 AJAX 未流行时,常用这种方法来伪装未刷新的效果,现在仍然可以使用。
要注意的是
enctype=”multipart/form-data”不可少,enctype 默认编码是“application/x-www-form-urlencoded”,设 enctype=”multipart/form-data”,用于二进制方式上传文件。
为防止文件名乱码,防止乱七八糟字符 URL 传递中出现问题,返回文件名到前台时进行 HttpUtility.UrlEncode,在前台 JS 中取文件名时进行 decodeURIComponent。
重置文件选择框时,要把文件选择框临时插入到临时表单,通过表单的 reset 方法重置。
本文地址 https://shaoshilei.com/2014-01/file-upload-without-refresh.html