先上几张图更直观展示一下要实现的功能。本功能主要通过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、JavaScriptclient实现代码

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

//文件上传事件方法
function Upload()
{
//假设有须要验证的能够在这里操作
UploadFile();
} //文件上传逻辑方法
function UploadFile()
{ //任务id,这里偷懒了直接复制页面server端空间生成后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 }, //传递參数到server
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

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

ajaxfileupload.js插件结合一般处理文件实现Ajax无刷新上传的更多相关文章

  1. Ajax 无刷新上传文件插件 uploadify 的使用

    在表单中无法直接使用 Ajax 上传文件,解决的思路可以是使用插件无刷新地上传文件,返回文件上传后的地址,然后把该地址作为 Ajax 的参数传递给服务器端进行数据库处理.可以使用 uploadify ...

  2. ajax无刷新上传文件

    网页上传文件最简单的方式就是通过表单上传了,但是在提交表单的时候会导致网页刷新,但有的时候我们不想网页刷新,有什么办法呢,我们可以使用ajax上传文件来做到这一点.只有ajax还不行,还需要JavaS ...

  3. jquery 的ajax无刷新上传文件之后,页面还是会莫名的刷新-----解决办法

    文件上传用到全局数组: $_FILES 只需要把下面的 <button onclick="post()">提交</button> 改为 <input ...

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

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

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

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

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

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

  7. 文件无刷新上传(swfUpload与uploadify)

    文件无刷新上传并获取保存到服务器端的路径 遇到上传文件的问题,结合之前用到过的swfUpload,又找了一个无刷新上传文件的jquery插件uploadify,写篇博客记录一下分别介绍这两个插件的实现 ...

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

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

  9. ajax +jsp+iframe无刷新上传文件[转]

    http://hi.baidu.com/zj360202/blog/item/f23e3711f929c774cb80c475.html ajax jsp 无刷新上传文件 2009-10-26 16: ...

随机推荐

  1. java输入输出高速

    头文件: import java.io.*; 定义: BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); ...

  2. 排列组合相关算法 python

    获取指定长度得全部序列 通过事件来表述这个序列,即n重伯努利实验(二项分布)的全部可能结果.比如时间a表示为: a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 假设每次实验为从 ...

  3. JDK源代码学习系列07----Stack

                                                                   JDK源代码学习系列07----Stack 1.Stack源代码很easy ...

  4. RH033读书笔记(2)-Lab 3 Getting Help with Commands

    Lab 3 Getting Help with Commands Sequence 1: Using the Help Tools 1. man -f keyword whatis keyword l ...

  5. linux文件打开模式

     文件打开 int open(const char *pathname, int flags, mode_t mode); 普通方式(Canonical mode) flags中没有设置O_SYN ...

  6. 剖析html对标准标签和自定义标签闭合与不闭合渲染问题

    昨天在修改去年写的系统的时候无意中看到了当时写的一个利用标准标签未闭合在单元格内把整个单元格颜色渲染成红色的效果,如下: 当时的问题是从后台返回来的是个int整数而%是写在页面上的如图 这 时候就出现 ...

  7. node.js基础:HTTP服务器

    一个HTTP服务器响应 var http = require('http'); http.createServer(function(request,response){ response.end(' ...

  8. c#中 uint--byte[]--char[]--string相互转换汇总

    原文:c#中 uint--byte[]--char[]--string相互转换汇总 在在做一些互操作的时候往往需要一些类型的相互转换,比如用c#访问win32api的时候往往需要向api中传入DWOR ...

  9. win7已安装Mysql 开机自启动

    1.下载并安装MySql,我用MySQL_5.6.24_winx64_XiaZaiBa,解压缩到磁盘或更低.我在这里安装D菜,D:\install\MySQL\MySQL Server 5.6. 2. ...

  10. Nagios显示器mysql定从库: libmysqlclient.so.18: cannot open shared object file: No such

    做mysql的slave时间监控,必须check_mysql文字,check当误差: error while loading shared libraries: libmysqlclient.so.1 ...