<% using (Html.BeginForm("importstu","Admin",FormMethod.Post,new{enctype="multipart/form-data",id="form"})) {%>
请选择上传的Excel文件:
<input id="upfile" type="file" name="upfile" style="width: 250px; background: White" class="easyui-validatebox" validtype="length[1,100]" />
<input type="submit" id="btn" value="上传" name="btn" style="width: 50px"/>
<%}%>
<script type="text/javascript">
$("#btn").bind("click", function () { //点击确定按钮的时候
var file = ($("#upfile").val());
if (file == "") {
$.messager.alert('系统提示', '请选择将要上传的文件!');
}
else {
var stuff = file.match(/^(.*)(\.)(.{1,8})$/)[3];
if (stuff != 'xls') {
alert('文件类型不正确,请选择.xls文件!');
}
else {
$('#form').form({
success: function (data) {
$.messager.alert('系统提示',data, 'info');
}
});
}
}
});
</script>
后台asp.net mvc:
[HttpPost]
public ActionResult importstu(HttpPostedFileBase upfile)
//upfile必须和前台input 的id一致
{
if (upfile != null)
{
if (upfile.ContentLength > 0)
{
string importfile = Server.MapPath("~/Uploaded/temp.xls");
string result = string.Empty;
upfile.SaveAs(importfile);
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + importfile + "; " + "Extended Properties=Excel 8.0;";
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet, "Students");
DataTable tab = myDataSet.Tables["Students"].DefaultView.ToTable();
foreach()
{
}
result = "导入成功!";
JsonResult json = new JsonResult();
json.Data = result;
return json;
}
else
return View();
}
else
return View();
}
前台:jquery实现form递交,并非xmlhttprequest上传文件,ajax上传文件只是用iframe模拟,ajax中的xmlhttprequest是无法上传文件的。
版权声明:本文为博主原创文章,未经博主允许不得转载。