首页 > 开发 > Javascript > 正文

asp.net+js 实现无刷新上传解析csv文件的代码

2020-02-28 04:10:57
字体:
来源:转载
供稿:网友
前阵子工作中用到,贴上代码,仅保留上传有关的代码,发现code其实很少。
上传页面html/js
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<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>

 
处理文件上传的c#
代码如下:
if (context.Request.Files.Count > 0)
{
HttpPostedFile file = context.Request.Files[0];
if (file.ContentLength > 0)
{
string title = string.Empty;
title = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Path.GetFileName(file.FileName);
string path = "./Upload/" + title;
path = System.Web.HttpContext.Current.Server.MapPath(path);
file.SaveAs(path);
context.Response.Write("<script>window.parent.FinishUpload('" + HttpUtility.UrlEncode(path) + "');</script>");
}
}
else
{
context.Response.Write("<script>window.parent.FinishUpload('');</script>");
}

  做到无刷新,基本原理就是:通过表单提交到iframe里,从而使刷新发生在iframe里。form设置action指向处理上传的文件,target指向iframe。上传操作的结果可以返回到iframe里,调用父对象的FinishUpload方法显示是否上传成功。所以在AJAX未流行时,常用这种方法来伪装未刷新的效果,现在仍然可以使用。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表