ajaxfileupload.js结合.ashx一般应用程序处理文件实现Ajax无刷新

先上几张图,本功能主要通过ajaxfileupload.js结合ajaxUpFile.ashx一般应用程序处理文件实现Ajax无刷新上传功能,结合NPOI2.0实现数据读取。

html页面js引用,需要引用jquery文件,我这里用到jquery-1.8.1.min.js和ajaxfileupload.js插件。

=>=>

html页面代码

====>====>=>></tr>

JavaScript文件代码

{UploadFile();}{//任务id var JobinfoId = jQuery(“#ctl00_ContentPlaceHolder1_hd_JobinfoId”).val();var PlanCode = jQuery(“#ctl00_ContentPlaceHolder1_hd_PlanCode”).val();var path = document.getElementById(“fu_UploadFile”).value;if ($.trim(path) == “”) { alert(“请选择要上传的文件”); return; }//弹出上传等待提示框hideReg(“div_error”); //隐藏错误提示jQuery(“#div_UpExcelLoading_msg”).html(“文件数据正在上传中,请耐心等待!”);showDialogue(“div_Confirm”);showReg(“div_UpExcelLoading”);var result_msg = “”;$.ajaxFileUpload({url: ‘Ajax/ajaxUpFile.ashx’,type: ‘post’,secureuri: false, //一般设置为falsefileElementId: ‘fu_UploadFile’, // 上传文件的id、name属性名dataType: ‘json’, //返回值类型,一般设置为json、application/jsondata: { “JobinfoId”: JobinfoId, “PlanCode”: PlanCode }, //传递参数到服务器success: result = eval(“[” + data + “]”);hideReg(“div_UpExcelLoading”);if (result[0].code == 3) {result_msg += “文件上传成功!”;var id = result[0].id;var name = result[0].file_name;//$(“#file_name”).html(result[0].file_name + “-下载”);$(“#plList_file”).append(“<label style=\”margin-left: 10px;\” title='” + name + “‘> <a href=\”#\” id=\”file_name” + id + “\” onclick=\”behaviorObj.DownloadFile(” + id + “);\”>” + name + “</a><img src=\”css/cupertino/images/cross_circle.png\” style=\”height: 10px; line-height: 10px;margin-left: 2px;\” alt=\”删除\” onclick=\”RemoveFile(” + id + “);\” /> </label>”);//alert(result_msg);jQuery(“#span_msg”).html(result_msg);showDialogue(“div_Confirm”);showReg(“div_error”);} else {//alert(result[0].msg);jQuery(“#span_msg”).html(result[0].msg);showDialogue(“div_Confirm”);showReg(“div_error”);}},error: alert(“错误:上传组件错误,请检察网络!”);}});}

ajaxUpFile.ashx代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.IO;using System.Net;using NPOI.SS.UserModel;using NPOI.HSSF.UserModel;using NPOI.XSSF.UserModel;using Marketing.Utility;using Newtonsoft.Json;using System.Text;using Marketing.BLL;using Marketing.Entity.DataModel;namespace Marketing.WebSite.Ajax{Summary description for ajaxUpFileajaxUpFile : IHttpHandler{//剔除数据上传表MdDatacubeofremovedetailBL _MdDatacubeofremovedetailBL = new MdDatacubeofremovedetailBL();//任务主表业务逻辑层MdDatacubeofjobinfoBL _MdDatacubeofjobinfoBL = new MdDatacubeofjobinfoBL();//文件上传记录表业务层MdDatacubeofremovefileBL _MdDatacubeofremovefileBL = new MdDatacubeofremovefileBL();(HttpContext context){var json = JsonConvert.SerializeObject(new { code = 0, msg = “操作失败” });context.Response.ContentType = HttpPostedFile _upfile = context.Request.Files[“fu_UploadFile”];if (_upfile != null){string result = FileUpLoad(_upfile);context.Response.Write(result);}}文件上传方法HttpPostedFile(HttpPostedFile file){var json = JsonConvert.SerializeObject(new { code = 0, msg = “” });//得到当前规则IDvar JobinfoId = HttpContext.Current.Request.Form[“JobinfoId”];//数据包号IDvar PlanCode = HttpContext.Current.Request.Form[“PlanCode”];int FType = 0;//文件类型string fileName, fileExtension;//文件名fileName = System.IO.Path.GetFileName(file.FileName);fileExtension = System.IO.Path.GetExtension(fileName).ToLower();int FileLen = file.ContentLength;Byte[] files = new Byte[FileLen];Stream sr = file.InputStream;//创建数据流对象 sr.Read(files, 0, FileLen);sr.Close();string fileType = Path.GetExtension(fileName).ToLower();if (!fileType.Equals(“.xlsx”) && !fileType.Equals(“.xls”)){json = JsonConvert.SerializeObject(new { code = 0, msg = “必须上传Excel文件” });}else{var emsg = string.Empty;string BatchNo = this.GenerateGUID();//得到唯一批号MdDatacubeofjobinfo MdDatacubeofjobinfoModel = _MdDatacubeofjobinfoBL.FindByPk(JobinfoId.ToInt(0));if (MdDatacubeofjobinfoModel != null){//验证数据IWorkbook workbook = null;using (MemoryStream ms = new MemoryStream(files, 0, files.Length)){FType = this._getFileType(fileName);if (FType == 2)//Office 2007以上{workbook = new XSSFWorkbook(ms); //将内存流转换为Excel对象}else if (FType == 1) //Office 2003{workbook = new HSSFWorkbook(ms);}}for (int i = 0; i < workbook.NumberOfSheets; i++) //遍历Sheet集{ISheet sheet = workbook.GetSheetAt(i); //获取当前Sheetif (sheet.LastRowNum > 0){if (sheet.GetRow(0).LastCellNum < 1){emsg += “模板列小于1列、”;}else if (!sheet.GetRow(0).Cells[0].StringCellValue.Trim().Equals(“主键”)){emsg += “缺少主键列、”;}}else{emsg += “无数据、”;}}if (!string.IsNullOrEmpty(emsg)){json = JsonConvert.SerializeObject(new { code = 0, msg = emsg.Substring(0, emsg.Length – 1) });}else{//文件上传string downloadPath = string.Empty;try{//序列化string json_flies = JsonConvert.SerializeObject(files);byte[] postArray = Encoding.UTF8.GetBytes(json_flies);downloadPath = FileWS.UploadFile(“Marketing_DataCube”, FileType.excel, postArray); //上传文件}catch (Exception ex){_logger.Error(“Excel文件上传异常”, ex, ErrorCode.ApplicationException);}if (string.IsNullOrEmpty(downloadPath)){json = JsonConvert.SerializeObject(new { code = 2, msg = “上传文件失败” });}else{try{DateTime tempTime = DateTime.Now;LogHelper.WriteLog(“upfile begin——–\n” + string.Format(“{0}已执开始”, tempTime));ISheet sheet = workbook.GetSheetAt(0); //获取当前Sheetif (sheet.LastRowNum > 0){//lastCellNum = sheet.GetRow(0).LastCellNum;//sheet.GetRow(0).CreateCell(lastCellNum, CellType.String).SetCellValue(“备注”);IList<MdDatacubeofremovedetail> MdDatacubeofremovedetailList = new List<MdDatacubeofremovedetail>();//上传文件上传成功for (int j = 1; j <= sheet.LastRowNum; j++) //遍历当前Sheet行{IRow row = sheet.GetRow(j); //读取当前行数据if (row != null){if (row.Cells.Count >= 1){row.Cells[0].SetCellType(CellType.String);FieldText = row.Cells[0].StringCellValue;MdDatacubeofremovedetail _MdDatacubeofremovedetailModel = new MdDatacubeofremovedetail();_MdDatacubeofremovedetailModel.JobinfoId = JobinfoId.ToInt(0);_MdDatacubeofremovedetailModel.PlanCode = PlanCode.ToString().Trim();_MdDatacubeofremovedetailModel.FieldDataType = MdDatacubeofjobinfoModel.ChannelType;_MdDatacubeofremovedetailModel.FieldText = FieldText.Trim();_MdDatacubeofremovedetailModel.BatchNo = BatchNo;_MdDatacubeofremovedetailModel.DataChange_CreateUser = AppParams.Instance.EID;_MdDatacubeofremovedetailModel.DataChange_CreateTime = DateTime.Now;MdDatacubeofremovedetailList.Add(_MdDatacubeofremovedetailModel);}}}if (MdDatacubeofremovedetailList.Count > 0){int pageSize = 100;int pageCount = 0;if (MdDatacubeofremovedetailList.Count >= pageSize){if (MdDatacubeofremovedetailList.Count % pageSize == 0){pageCount = MdDatacubeofremovedetailList.Count / pageSize;}else{pageCount = MdDatacubeofremovedetailList.Count / pageSize + 1;}}else{pageCount = 1;}for (int j = 0; j < pageCount; j++) //遍历当前Sheet行{IList<MdDatacubeofremovedetail> list = MdDatacubeofremovedetailList.Skip(j * pageSize).Take(pageSize).ToList();bool count = _MdDatacubeofremovedetailBL.BulkInsert(list);}//记录文件上传名MdDatacubeofremovefile MdDatacubeofremovefileModel = new MdDatacubeofremovefile();MdDatacubeofremovefileModel.BatchNo = BatchNo;MdDatacubeofremovefileModel.JobinfoId = JobinfoId.ToInt(0);MdDatacubeofremovefileModel.PlanCode = PlanCode.ToString().Trim();MdDatacubeofremovefileModel.ImportFileName = fileName;MdDatacubeofremovefileModel.ImportFileNameUrl = downloadPath;MdDatacubeofremovefileModel.FileType = FType;MdDatacubeofremovefileModel.DataChange_CreateTime = DateTime.Now;MdDatacubeofremovefileModel.DataChange_CreateUser = AppParams.Instance.EID;long count_id = _MdDatacubeofremovefileBL.InsertMdDatacubeofremovefile(MdDatacubeofremovefileModel);LogHelper.WriteLog(“upfile end——–\n” + string.Format(“{0}已执行完成, 耗时{1}/ms”,DateTime.Now.ToString(“yyyy-MM-dd HH:mm:ss”), TimeHelper.GetDifferMilliSecond(tempTime)));json = JsonConvert.SerializeObject(new { code = 3, msg = “文件上传成功”, file_name = fileName, id = count_id });}}}catch (Exception ex){_logger.Error(“Excel文件读取或写入异常”, ex, ErrorCode.ApplicationException);json = JsonConvert.SerializeObject(new { code = 0, msg = “数据写入异常” });}}}}}return json;}生成GUID3、Guid.NewGuid().ToString(“B”) 结果为:{09f140d5-af72-44ba-a763-c861304b46f8}(){return System.Guid.NewGuid().ToString(“N”);}Description:Author: 付义方文件类型 `_getFileType(string uploadFileName){if (uploadFileName.IndexOf(“.xlsx”) != -1)return 2;else if (uploadFileName.IndexOf(“.xls”) != -1)return 1;else if (uploadFileName.IndexOf(“.txt”) != -1)return 3;else if (uploadFileName.IndexOf(“.csv”) != -1)return 4;Exception(string.Format(“{0}为未知文件类型”, uploadFileName));}public bool IsReusable{get{return false;}}}}

,“人无完人金无足赤”,只要是人就不会是完美的,

ajaxfileupload.js结合.ashx一般应用程序处理文件实现Ajax无刷新

相关文章:

你感兴趣的文章:

标签云: