Jquery ajaxfileupload.js结合.ashx文件实现无刷新上传

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

一、功能页面布局及介绍

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

Jquery ajaxfileupload.js结合.ashx文件实现无刷新上传

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

Jquery ajaxfileupload.js结合.ashx文件实现无刷新上传

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

Jquery ajaxfileupload.js结合.ashx文件实现无刷新上传

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

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文件实现无刷新上传

上一篇:nginx上传模块nginx_upload_module使用


下一篇:uni-app的多环境部署配置