先上几张图更直观展示一下要实现的功能,本功能主要通过Jquery ajaxfileupload.js插件结合ajaxUpFile.ashx一般应用程序处理文件实现Ajax无刷新上传功能,结合NPOI2.0实现数据读取。这个功能在实际工作种经常用到,希望能给需要做这方面的人有些帮助。

一、功能页面布局及介绍

1、上传页面布局及input file上传功能

2、上传页面文件正在上传效果

3、上传完成效果,多文件展示区

二、功能代码实现及资源引用

1、js资源文件引用

html页面js引用,需要引用jquery文件,我这里用到jquery-1.8.1.min.js和ajaxfileupload.js插件。ajaxfileupload.js插件下载地址:http://download.csdn.net/detail/fuyifang/8534801

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

2、html页面实现代码

采用html+jquey ajax方式去实现上传功能,可以下载Excel导入模版;

<tr>
<td>
<div class="inlin-label-box">
<label>选择剔除用户:</label>
<label style=" width:220px;">
<input type="file" id="fu_UploadFile" name="fu_UploadFile" style="height:26px;" /></label>
<label><input type="button" onclick="Upload()" value="上传"  style="height: 26px; padding: 0px 10px 0px 10px;margin-left:10px;"  class="btn" /></label><span class="tip-inline">(<a href="Template/剔除上传数据导入格式.xlsx">下载Excel导入模板</a>)</span>
<label>
<iframe src="" id="downloadFrame" style="display: none;"></iframe>
</label>
</div>
</td>
</tr>

3、JavaScript客户端实现代码

ajaxfileupload.js结合ajaxUpFile.ashx一般应用程序处理文件实现Ajax无刷新上传功能并且显示灰色遮罩;

//文件上传事件方法
function Upload()
{
    //如果有需要验证的可以在这里操作
    UploadFile();
}

//文件上传逻辑方法
function UploadFile()
{

    //任务id,这里偷懒了直接复制页面服务器端空间生成后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("<label style='white-space: normal;overflow: hidden;cursor: pointer;' id='lb_" + id + "' style=\"margin-left: 10px;\" title='" + name + "'> <a href=\"#\" id=\"file_name" + id + "\" onclick=\"behaviorObj.DownloadFile(" + id + ");\">" + name + "</a><img id='img_" + id + "' 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: function (data, status, e) {
            // alert(e);
            alert("错误:上传组件错误,请检察网络!");
        }
    });
}

4、ajaxUpFile.ashx实现代码

这个地方值得注意的是需要读取Excel文件,需要引用NPOI的dll,这个可以在百度上搜索一下,尽量采用新版本,兼容性好。

也可以在CSDN下载NOPI,下载地址:http://download.csdn.net/detail/xiaopenglin/4365472

需要引用的NPOI的命名空间如下:

using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using Marketing.Utility;
using Newtonsoft.Json;

C# Excel读取写入等功能实现代码:

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>
    /// Summary description for ajaxUpFile
    /// </summary>
    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);
            }

        }

        /// <summary>
        ///文件上传方法
        /// </summary>
        /// <param name="file">HttpPostedFile</param>
        /// <returns></returns>
        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<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);
                                                //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<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;

        }

        /// <summary>
        /// 生成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)
        /// </summary>
        /// <returns></returns>
        private string GenerateGUID()
        {
            return System.Guid.NewGuid().ToString("N");
        }

        /// <summary>
        /// Description:
        /// 1. 获取文件类型
        /// 2. 私有函数
        /// Author     : 付义方
        /// Create Date: 2014-02-09
        /// </summary>
        /// <param name="uploadFileName">上传文件名</param>
        /// <returns>文件类型   `</returns>
        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;
            }
        }
    }
}

以上希望多各位需要做ajax文件上传的朋友有些帮助,谢谢!

更多关注付义方技术博客:http://blog.csdn.net/fuyifang

或者直接用手机扫描二维码查看更多博文:

Jquery ajaxfileupload.js结合.ashx文件实现无刷新上传的更多相关文章

  1. ASP.NET MVC 使用Uploadify实现多文件异步无刷新上传

    软件技术开发,合作请联系QQ:858-048-581 这里我通过使用uploadify组件来实现异步无刷新多文件上传功能. 1.首先下载组件包uploadify,我这里使用的版本是3.1 2.下载后解 ...

  2. 拖拽文件实现无刷新上传,支持2G文件

    客户端 用HTML5:jQuery File Upload http://blueimp.github.io/jQuery-File-Upload/basic-plus.html API https: ...

  3. ajaxfileupload.js插件结合一般处理文件实现Ajax无刷新上传

    先上几张图更直观展示一下要实现的功能.本功能主要通过Jquery ajaxfileupload.js插件结合ajaxUpFile.ashx一般应用程序处理文件实现Ajax无刷新上传功能,结合NPOI2 ...

  4. SpringMVC结合ajaxfileupload.js实现文件无刷新上传

    直接看代码吧,注释都在里面 首先是web.xml <?xml version="1.0" encoding="UTF-8"?> <web-ap ...

  5. [Asp.net mvc]jquery.form.js无刷新上传

    写在前面 最近在自己的网盘项目中想用ajax.beginform的方式做无刷新的操作,提交表单什么的都可以,但针对文件上传,就是个鸡肋.在网上查找了发现很多人都遇到了这个问题,大部分都推荐使用jque ...

  6. jquery ajax php 无刷新上传文件 带 遮罩 进度条 效果的哟

    在很多项目中都会叫用户上传东西这些的,自从接触了jquery 和ajax之后就不管做什么,首先都会想到这个,我这个人呢?是比较重视客户体验的,这次我这边负责的是后台板块,然后就有一块是要求用户上传照片 ...

  7. jQuery+php+ajax实现无刷新上传文件功能

    jQuery+php+ajax实现无刷新上传文件功能,还带有上传进度条动画效果,支持图片.视频等大文件上传. js代码 <script type='text/javascript' src='j ...

  8. jQuery AJAX 网页无刷新上传示例

    新年礼,提供简单.易套用的 jQuery AJAX 上传示例及代码下载.后台对文件的上传及检查,以 C#/.NET Handler 处理 (可视需要改写成 Java 或 PHP). 有时做一个网站项目 ...

  9. ASP.NET MVC使用jQuery无刷新上传

    昨晚网友有下载了一个jQuery无刷新上传的小功能,他尝试搬至ASP.NET MVC应用程序中去,在上传死活无效果.Insus.NET使用Teamviewer远程桌面,操作一下,果真是有问题.网友是说 ...

随机推荐

  1. ansible基础及使用示例

    1 介绍 Ansible 是一个系统自动化工具,用来做系统配管理,批量对远程主机执行操作指令. 2 实验环境 ip 角色 192.168.40.71 ansible管控端 192.168.40.72 ...

  2. ABP官方文档翻译 3.4 领域服务

    领域服务 介绍 IDomainService接口和DomainService类 示例 创建接口 服务实现 使用应用服务 一些探讨 为什么只有应用服务? 如何强制使用领域服务? 介绍 领域服务(或者在D ...

  3. xBIM 格式之间转换

    目录 xBIM 应用与学习 (一) xBIM 应用与学习 (二) xBIM 基本的模型操作 xBIM 日志操作 XBIM 3D 墙壁案例 xBIM 格式之间转换 xBIM 使用Linq 来优化查询 x ...

  4. SDN第四次作业

    作业链接 1.阅读 了解SDN控制器的发展 http://www.sdnlab.com/13306.html http://www.docin.com/p-1536626509.html 了解ryu控 ...

  5. CNN网络架构演进:从LeNet到DenseNet

    卷积神经网络可谓是现在深度学习领域中大红大紫的网络框架,尤其在计算机视觉领域更是一枝独秀.CNN从90年代的LeNet开始,21世纪初沉寂了10年,直到12年AlexNet开始又再焕发第二春,从ZF ...

  6. Docker小记 — Docker Engine

    前言 用了Docker方才觉得生产环境终于有了他该有的样子,就像集装箱普及之后大型货轮的价值才逐渐体现出来,Docker详细说明可查阅"官方文档".本篇为Docker Engine ...

  7. S5PV210时钟,看门狗定时器

    晶振:时钟源(操作主要有两个,倍频,分频) A8的时钟源: 时钟域,每个时钟域(不同的最高频率和最低频率)管理着不同的电路模块: 不同的时钟域对应不同电路模块表 时钟电路:懂得看时钟电路(时钟源选择开 ...

  8. Netty ByteBuf梳理

    我们知道,网络数据的基本单位总是字节.Java NIO提供了ByteBuffer作为它的字节容器,但是这个类使用起来过于复杂,而且也有些繁琐. Netty的ByteBuffer替代品是ByteBuf, ...

  9. CENTOS/RHEL 7 系统中设置SYSTEMD SERVICE的ULIMIT资源限制

    遇到的问题: golang程序一直出现 too many open files的报错, 尽管对 /etc/security/limits.conf 做了设置, 对最大文件打开数,最大进程数做了调优. ...

  10. JVM性能监控与故障处理命令汇总(jps、jstat、jinfo、jmap、jhat、jstack)

    给一个系统定位问题的时候,知识.经验是关键基础,数据是依据,工具才是运用知识处理数据的手段 使用适当的虚拟机监控和分析的工具可以加快我们分析数据.定位解决问题的速度,本文主要介绍了几款服 务器上常用的 ...