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

页面导航:首页 > 网络编程 > JavaScript > ajaxfileupload.js结合.ashx一般处理文件实现Ajax无刷新

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

来源: 作者: 时间:2016-02-02 09:59 【

先上几张图,本功能主要通过ajaxfileupload js结合ajaxUpFile ashx一般应用程序处理文件实现Ajax无刷新上传功能,结合NPOI2 0实现数据读取。1、上传页面input file 2、上传页面正在上传效果 3、上

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

1、上传页面input file
Excel文件上传和读取-1

2、上传页面正在上传效果
Excel文件上传和读取-2

3、上传完成效果,多文件展示区
Excel文件上传和读取-3

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

<script src="js/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="js/ajaxfileupload.js" type="text/javascript"></script>

html页面代码



()

JavaScript文件代码

//文件上传事件方法
function Upload()
{
    UploadFile();
}

//文件上传逻辑方法
function 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, //一般设置为false
        fileElementId: 'fu_UploadFile', // 上传文件的id、name属性名
        dataType: 'json', //返回值类型,一般设置为json、application/json
        data: { "JobinfoId": JobinfoId, "PlanCode": PlanCode }, //传递参数到服务器
        success: function (data, status) {

            var 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("");
                //alert(result_msg);
                jQuery("#span_msg").(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: function (data, status, e) {
            // alert(e);
            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 ajaxUpFile
    /// 
    public class ajaxUpFile : IHttpHandler
    {
        //剔除数据上传表
        MdDatacubeofremovedetailBL _MdDatacubeofremovedetailBL = new MdDatacubeofremovedetailBL();
        //任务主表业务逻辑层
        MdDatacubeofjobinfoBL _MdDatacubeofjobinfoBL = new MdDatacubeofjobinfoBL();
        //文件上传记录表业务层
        MdDatacubeofremovefileBL _MdDatacubeofremovefileBL = new MdDatacubeofremovefileBL();
        private static CLogger _logger = new CLogger("AjaxUpFile"); //声明日志记录对象
        public void ProcessRequest(HttpContext context)
        {
            var json = JsonConvert.SerializeObject(new { code = 0, msg = "操作失败" });
            context.Response.ContentType = "text/html";//这里很关键,虽然前台数据类型是json,但这里一定要写html  
            //获取前台传来的文件  
            //HttpFileCollection files = HttpContext.Current.Request.Files;

            HttpPostedFile _upfile = context.Request.Files["fu_UploadFile"];
            if (_upfile != null)
            {
                string result = FileUpLoad(_upfile);
                context.Response.Write(result);
            }


        }

        /// 
        ///文件上传方法
        /// 
        ///HttpPostedFile
        /// 
        private string FileUpLoad(HttpPostedFile file)
        {
            var json = JsonConvert.SerializeObject(new { code = 0, msg = "" });
            //得到当前规则ID
            var JobinfoId = HttpContext.Current.Request.Form["JobinfoId"];
            //数据包号ID
            var 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);   //获取当前Sheet

                        if (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);   //获取当前Sheet

                                if (sheet.LastRowNum > 0)
                                {

                                    //lastCellNum = sheet.GetRow(0).LastCellNum;
                                    //sheet.GetRow(0).CreateCell(lastCellNum, CellType.String).SetCellValue("备注");

                                    IList MdDatacubeofremovedetailList = new List();
                                    //上传文件上传成功
                                    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);
                                                //row.Cells[2].SetCellType(CellType.String);
                                                //row.Cells[3].SetCellType(CellType.String);

                                                var FieldText = row.Cells[0].StringCellValue;
                                                //uid = row.Cells[2].StringCellValue;
                                                //originalUrl = row.Cells[3].StringCellValue;

                                                //ICell srCell = row.CreateCell(lastCellNum, CellType.String);
                                                //srCell.SetCellValue("备注"); //设置备注
                                                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 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;

        }

        /// 
        /// 生成GUID
        /// 1、Guid.NewGuid().ToString("N") 结果为:       38bddf48f43c48588e0d78761eaa1ce6
        /// 2、Guid.NewGuid().ToString("D") 结果为:        57d99d89-caab-482a-a0e9-a0a803eed3ba
        /// 3、Guid.NewGuid().ToString("B") 结果为:      {09f140d5-af72-44ba-a763-c861304b46f8}
        /// 4、Guid.NewGuid().ToString("P") 结果为:      (778406c2-efff-4262-ab03-70a77d09c2b5)
        /// 
        /// 
        private string GenerateGUID()
        {
            return System.Guid.NewGuid().ToString("N");
        }



        /// 
        /// Description:
        /// 1. 获取文件类型
        /// 2. 私有函数
        /// Author     : 付义方
        /// Create Date: 2014-02-09
        /// 
        ///上传文件名
        /// 文件类型   `
        private byte _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;
            else
                throw new Exception(string.Format("{0}为未知文件类型", uploadFileName));
        }



        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
Tags:

文章评论

最 近 更 新
热 点 排 行
Js与CSS工具
代码转换工具

<