1.新增引用:
<script type="text/javascript" src="/scripts/ajaxfileupload.js"></script>2.新增控件:
<asp:FileUpload ID="fup" runat="server" Width="70"></asp:FileUpload> <input id="Button1" type="button" value="导入" onclick="Upload()"/>3.Upload()方法:
<script type="text/javascript"> function Upload() { var file = $("#fup").val(); if (file == "") { alert("请选择上传的文件"); return; } $.ajaxFileUpload( { url: '/Pages/QzSpecialistic/Destroy.ashx',//需要链接到服务器地址 secureuri: false,fileElementId: 'fup',//文件选择框的id属性 dataType: 'json',success: function (data) { if (data.status == "success") { alert(data.msg); //$('#grid').datagrid('reload'); window.location.href = "DestroyDetail.aspx"; } else { alert(data.msg); } },error: function (data,status,e) { alert(e); //就是在这弹出“语法错误” } } ); } </script>
4.Destroy.ashx实现(先读取文件再保存文件)
public void ProcessRequest(HttpContext context) { context.Response.Clear(); HttpFileCollection postedFile = context.Request.Files; //判断是否有数据 if (postedFile != null && postedFile.Count > 0) { int length = postedFile[0].ContentLength;//文件大小 string filename = System.IO.Path.GetFileName(postedFile[0].FileName);//文件名 if (length > 0 && length < 512000) { string type = System.IO.Path.GetExtension(postedFile[0].FileName);//文件类型 if (type == ".xml") { //读取文件 QZ_SPECIALISTIC_ALLOCATION model = new QZ_SPECIALISTIC_ALLOCATION(); QzSpecialisticDAL dal = new QzSpecialisticDAL(); DataSet xmlDS = new DataSet(); XmlTextReader reader = null; try { //加载xml -->取消根据路径读取XML方式 //XmlDocument xmlDoc = new XmlDocument(); //xmlDoc.Load(path+filename); //path+filename为文件路径 //StringReader stream = new StringReader(xmlDoc.InnerXml); //从stream装载到XmlTextReader //XmlTextReader reader = new XmlTextReader(stream); //直接读取文件内容 byte[] input = new byte[length]; System.IO.Stream UpLoadStream = postedFile[0].InputStream; UpLoadStream.Read(input,length); UpLoadStream.Position = 0; System.IO.StreamReader sr = new System.IO.StreamReader(UpLoadStream,System.Text.Encoding.Default); //将xml文件转换为DataSet reader = new XmlTextReader(sr); xmlDS.ReadXml(reader); for (int i = 0; i < xmlDS.Tables[0].Rows.Count; i++) { model.ID = xmlDS.Tables[0].Rows[i]["ID"].ToString();//主键ID if (!dal.AddOutDetailTemp(model))//插入数据库 { string res = "{\"status\" : \"error\",\"msg\": \"数据录入失败!\"}"; context.Response.Write(res); return; } } string path = HttpContext.Current.Server.MapPath("/XmlFiles/");//文件存放路径 if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path);//创建文件夹 postedFile[0].SaveAs(path + filename);//保存文件内容 string res1 = "{\"status\" : \"success\",\"msg\": \"上传成功!\"}"; context.Response.Write(res1); } catch { string res = "{\"status\" : \"error\",\"msg\": \"数据库插入失败!\"}"; context.Response.Write(res); return; } } else { string res = "{\"status\" : \"error\",\"msg\": \"只允许上传.xml类型的文件!\"}"; context.Response.Write(res); return; } } else { string res = "{\"status\" : \"error\",\"msg\": \"文件过大!\"}"; context.Response.Write(res); return; } } }原文链接:https://www.f2er.com/ajax/162530.html