1、bootstrap-fileinpu的簡(jiǎn)單介紹
在前面的隨筆,我介紹了Bootstrap-table表格插件的具體項(xiàng)目應(yīng)用過程,本篇隨筆介紹另外一個(gè)Bootstrap FieInput插件的使用,整合兩者可以實(shí)現(xiàn)我們常規(guī)的Web數(shù)據(jù)導(dǎo)入操作,導(dǎo)入數(shù)據(jù)操作過程包括有上傳文件,預(yù)覽數(shù)據(jù),選擇并提交記錄等一系列操作。
關(guān)于這個(gè)插件,我在早期隨筆《Bootstrap文件上傳插件File Input的使用》也做了一次介紹,這是一個(gè)增強(qiáng)的 HTML5 文件輸入控件,是一個(gè) Bootstrap 3.x 的擴(kuò)展,實(shí)現(xiàn)文件上傳預(yù)覽,多文件上傳等功能。
bootstrap-fileinput源碼:https://github.com/kartik-v/bootstrap-fileinput
bootstrap-fileinput在線API:http://plugins.krajee.com/file-input
bootstrap-fileinput Demo展示:http://plugins.krajee.com/file-basic-usage-demo
這個(gè)插件主要是介紹如何處理圖片上傳的處理操作,原先我的Excel導(dǎo)入操作使用的是Uploadify插件,可以參考我隨筆《附件上傳組件uploadify的使用》,不過這個(gè)需要Flash控件支持,在某些瀏覽器(如Chrome)就比較麻煩了,因此決定使用一種較為通用的上傳插件,這次首先對(duì)基于Bootstrap前端架構(gòu)的框架系統(tǒng)進(jìn)行升級(jí),替代原來的Uploadify插件,這樣頁面上傳功能,在各個(gè)瀏覽器就可以無差異的實(shí)現(xiàn)了。
一般情況下,我們需要引入下面兩個(gè)文件,插件才能正常使用:
bootstrap-fileinput/css/fileinput.min.css
bootstrap-fileinput/js/fileinput.min.js
在File input 插件使用的時(shí)候,如果是基于Asp.NET MVC的,那么我們可以使用BundleConfig.cs進(jìn)行添加對(duì)應(yīng)的引用,加入到Bundles集合引用即可。
//添加對(duì)bootstrap-fileinput控件的支持
css_metronic.Include("~/Content/MyPlugins/bootstrap-fileinput/css/fileinput.min.css");
js_metronic.Include("~/Content/MyPlugins/bootstrap-fileinput/js/fileinput.min.js");
js_metronic.Include("~/Content/MyPlugins/bootstrap-fileinput/js/locales/zh.js");
在頁面中,我們使用以下HTML代碼實(shí)現(xiàn)界面展示,主要的bootstrap fileinput插件聲明,主要是基礎(chǔ)的界面代碼
<input id="excelFile" type="file">
Excel導(dǎo)入的的界面展示如下所示。
選擇指定文件后,我們可以看到Excel的文件列表,如下界面所示。
上傳文件后,數(shù)據(jù)直接展示在彈出層的列表里面,這里直接使用了 Bootstrap-table表格插件進(jìn)行展示。
這樣我們就可以把Excel的記錄展示出來,實(shí)現(xiàn)了預(yù)覽的功能,勾選必要的記錄,然后保存即可提交到服務(wù)器進(jìn)行保存,實(shí)現(xiàn)了Excel數(shù)據(jù)的真正導(dǎo)入數(shù)據(jù)庫處理。
2、Excel導(dǎo)出操作詳細(xì)介紹
我們?cè)趯?shí)際導(dǎo)入Excel的界面中,HTML代碼如下所示。
<!--導(dǎo)入數(shù)據(jù)操作層-->
<div id="import" class="modal fade bs-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">文件導(dǎo)入</h4>
</div>
<div class="modal-body">
<div style="text-align:right;padding:5px">
<a href="~/Content/Template/TestUser-模板.xls" onclick="javascript:Preview();">

<span style="font-size:larger;font-weight:200;color:red">TestUser-模板.xls</span>
</a>
</div>
<hr/>
<form id="ffImport" method="post">
<div title="Excel導(dǎo)入操作" style="padding: 5px">
<input type="hidden" id="AttachGUID" name="AttachGUID" />
<input id="excelFile" type="file">
</div>
</form>
<!--數(shù)據(jù)顯示表格-->
<table id="gridImport" class="table table-striped table-bordered table-hover" cellpadding="0" cellspacing="0" border="0">
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">關(guān)閉</button>
<button type="button" class="btn btn-primary" onclick="SaveImport()">保存</button>
</div>
</div>
</div>
</div>
對(duì)于bootstrap fileinput的各種屬性,我們這里使用JS進(jìn)行初始化,這樣方便統(tǒng)一管理和修改。
//初始化Excel導(dǎo)入的文件
function InitExcelFile() {
//記錄GUID
$("#AttachGUID").val(newGuid());
$("#excelFile").fileinput({
uploadUrl: "/FileUpload/Upload",//上傳的地址
uploadAsync: true, //異步上傳
language: "zh", //設(shè)置語言
showCaption: true, //是否顯示標(biāo)題
showUpload: true, //是否顯示上傳按鈕
showRemove: true, //是否顯示移除按鈕
showPreview : true, //是否顯示預(yù)覽按鈕
browseClass: "btn btn-primary", //按鈕樣式
dropZoneEnabled: false, //是否顯示拖拽區(qū)域
allowedFileExtensions: ["xls", "xlsx"], //接收的文件后綴
maxFileCount: 1, //最大上傳文件數(shù)限制
previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
allowedPreviewTypes: null,
previewFileIconSettings: {
'docx': '<i class="glyphicon glyphicon-file"></i>',
'xlsx': '<i class="glyphicon glyphicon-file"></i>',
'pptx': '<i class="glyphicon glyphicon-file"></i>',
'jpg': '<i class="glyphicon glyphicon-picture"></i>',
'pdf': '<i class="glyphicon glyphicon-file"></i>',
'zip': '<i class="glyphicon glyphicon-file"></i>',
},
uploadExtraData: { //上傳的時(shí)候,增加的附加參數(shù)
folder: '數(shù)據(jù)導(dǎo)入文件', guid: $("#AttachGUID").val()
}
}) //文件上傳完成后的事件
.on('fileuploaded', function (event, data, previewId, index) {
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
var res = data.response; //返回結(jié)果
if (res.Success) {
showTips('上傳成功');
var guid = $("#AttachGUID").val();
//提示用戶Excel格式是否正常,如果正常加載數(shù)據(jù)
$.ajax({
url: '/TestUser/CheckExcelColumns?guid=' + guid,
type: 'get',
dataType: 'json',
success: function (data) {
if (data.Success) {
InitImport(guid); //重新刷新表格數(shù)據(jù)
showToast("文件已上傳,數(shù)據(jù)加載完畢!");
//重新刷新GUID,以及清空文件,方便下一次處理
RefreshExcel();
}
else {
showToast("上傳的Excel文件檢查不通過。請(qǐng)根據(jù)頁面右上角的Excel模板格式進(jìn)行數(shù)據(jù)錄入。", "error");
}
}
});
}
else {
showTips('上傳失敗');
}
});
}
上面的邏輯具體就是,設(shè)置上傳文件的后臺(tái)頁面為:/FileUpload/Upload,以及各種插件的配置參數(shù),uploadExtraData里面設(shè)置的是提交的附加參數(shù),也就是后臺(tái)控制器接收的參數(shù),其中
.on('fileuploaded', function (event, data, previewId, index) {
的函數(shù)處理文件上傳后的處理函數(shù),如果上傳文件返回的結(jié)果是成功的,那么我們?cè)俅握{(diào)用ajax來檢查這個(gè)Excel的字段是否符合要求,如下地址:
url: '/TestUser/CheckExcelColumns?guid=' + guid,
如果這個(gè)檢查的后臺(tái)返回成功的記錄,那么再次需要把Excel記錄提取出來預(yù)覽,并清空bootstrap fileinput文件上傳插件,方便下次上傳文件。如下代碼所示。
if (data.Success) {
InitImport(guid); //重新刷新表格數(shù)據(jù)
showToast("文件已上傳,數(shù)據(jù)加載完畢!");
//重新刷新GUID,以及清空文件,方便下一次處理
RefreshExcel();
}
else {
showToast("上傳的Excel文件檢查不通過。請(qǐng)根據(jù)頁面右上角的Excel模板格式進(jìn)行數(shù)據(jù)錄入。", "error");
}
其中RefreshExcel就是重新更新上傳的附加參數(shù)值,方便下次上傳,否則附加參數(shù)的值一直不變化,就會(huì)導(dǎo)致我們?cè)O(shè)置的GUID沒有變化而出現(xiàn)問題。
//重新更新GUID的值,并清空文件
function RefreshExcel() {
$("#AttachGUID").val(newGuid());
$('#excelFile').fileinput('clear');//清空所有文件
//附加參數(shù)初始化后一直不會(huì)變化,如果需要發(fā)生變化,則需要使用refresh進(jìn)行更新
$('#excelFile').fileinput('refresh', {
uploadExtraData: { folder: '數(shù)據(jù)導(dǎo)入文件', guid: $("#AttachGUID").val() },
});
}
而其中InitImport就是獲取預(yù)覽數(shù)據(jù)并展示在Bootstrap-table表格插件上的,關(guān)于這個(gè)插件的詳細(xì)使用,可以回顧下隨筆《基于Metronic的Bootstrap開發(fā)框架經(jīng)驗(yàn)總結(jié)(16)-- 使用插件bootstrap-table實(shí)現(xiàn)表格記錄的查詢、分頁、排序等處理》進(jìn)行了解即可。
//根據(jù)條件查詢并綁定結(jié)果
var $import;
function InitImport(guid) {
var url = "/TestUser/GetExcelData?guid=" + guid;
$import = $('#gridImport').bootstrapTable({
url: url, //請(qǐng)求后臺(tái)的URL(*)
method: 'GET', //請(qǐng)求方式(*)
striped: true, //是否顯示行間隔色
cache: false, //是否使用緩存,默認(rèn)為true,所以一般情況下需要設(shè)置一下這個(gè)屬性(*)
pagination: false, //是否顯示分頁(*)
sidePagination: "server", //分頁方式:client客戶端分頁,server服務(wù)端分頁(*)
pageNumber: 1, //初始化加載第一頁,默認(rèn)第一頁,并記錄
pageSize: 100, //每頁的記錄行數(shù)(*)
pageList: [10, 25, 50, 100], //可供選擇的每頁的行數(shù)(*)
search: false, //是否顯示表格搜索
strictSearch: true,
showColumns: true, //是否顯示所有的列(選擇顯示的列)
showRefresh: true, //是否顯示刷新按鈕
minimumCountColumns: 2, //最少允許的列數(shù)
clickToSelect: true, //是否啟用點(diǎn)擊選中行
uniqueId: "ID", //每一行的唯一標(biāo)識(shí),一般為主鍵列
queryParams: function (params) { },
columns: [{
checkbox: true,
visible: true //是否顯示復(fù)選框
}, {
field: 'Name',
title: '姓名'
}, {
field: 'Mobile',
title: '手機(jī)'
}, {
field: 'Email',
title: '郵箱',
formatter: emailFormatter
}, {
field: 'Homepage',
title: '主頁',
formatter: linkFormatter
}, {
field: 'Hobby',
title: '興趣愛好'
}, {
field: 'Gender',
title: '性別',
formatter: sexFormatter
}, {
field: 'Age',
title: '年齡'
}, {
field: 'BirthDate',
title: '出生日期',
formatter: dateFormatter
}, {
field: 'Height',
title: '身高'
}, {
field: 'Note',
title: '備注'
}],
onLoadSuccess: function () {
},
onLoadError: function () {
showTips("數(shù)據(jù)加載失敗!");
},
});
}
最后就是確認(rèn)提交后,會(huì)通過JS提交數(shù)據(jù)到后臺(tái)進(jìn)行處理,如下代碼所示。
//保存導(dǎo)入的數(shù)據(jù)
function SaveImport() {
var list = [];//構(gòu)造集合對(duì)象
var rows = $import.bootstrapTable('getSelections');
for (var i = 0; i < rows.length; i++) {
list.push({
'Name': rows[i].Name, 'Mobile': rows[i].Mobile, 'Email': rows[i].Email, 'Homepage': rows[i].Homepage,
'Hobby': rows[i].Hobby, 'Gender': rows[i].Gender, 'Age': rows[i].Age, 'BirthDate': rows[i].BirthDate,
'Height': rows[i].Height, 'Note': rows[i].Note
});
}
if (list.length == 0) {
showToast("請(qǐng)選擇一條記錄", "warning");
return;
}
var postData = { 'list': list };//可以增加其他參數(shù),如{ 'list': list, 'Rucanghao': $("#Rucanghao").val() };
postData = JSON.stringify(postData);
$.ajax({
url: '/TestUser/SaveExcelData',
type: 'post',
dataType: 'json',
contentType: 'application/json;charset=utf-8',
traditional: true,
success: function (data) {
if (data.Success) {
//保存成功 1.關(guān)閉彈出層,2.清空記錄顯示 3.刷新主列表
showToast("保存成功");
$("#import").modal("hide");
$(bodyTag).html("");
Refresh();
}
else {
showToast("保存失敗:" + data.ErrorMessage, "error");
}
},
data: postData
});
}
3、后臺(tái)控制器代碼分析
這里我們的JS代碼里面,涉及了幾個(gè)MVC后臺(tái)的方法處理:Upload、CheckExcelColumns、GetExcelData、SaveExcelData。這里分別進(jìn)行介紹。
文件上傳的后臺(tái)控制器方法如下所示。
/// <summary>
/// 上傳附件到服務(wù)器上
/// </summary>
/// <param name="fileData">附件信息</param>
/// <param name="guid">附件組GUID</param>
/// <param name="folder">指定的上傳目錄</param>
/// <returns></returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Upload(string guid, string folder)
{
CommonResult result = new CommonResult();
HttpFileCollectionBase files = HttpContext.Request.Files;
if (files != null)
{
foreach (string key in files.Keys)
{
try
{
#region MyRegion
HttpPostedFileBase fileData = files[key];
if (fileData != null)
{
HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8");
HttpContext.Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
HttpContext.Response.Charset = "UTF-8";
// 文件上傳后的保存路徑
string filePath = Server.MapPath("~/UploadFiles/");
DirectoryUtil.AssertDirExist(filePath);
string fileName = Path.GetFileName(fileData.FileName); //原始文件名稱
string fileExtension = Path.GetExtension(fileName); //文件擴(kuò)展名
//string saveName = Guid.NewGuid().ToString() + fileExtension; //保存文件名稱
FileUploadInfo info = new FileUploadInfo();
info.FileData = ReadFileBytes(fileData);
if (info.FileData != null)
{
info.FileSize = info.FileData.Length;
}
info.Category = folder;
info.FileName = fileName;
info.FileExtend = fileExtension;
info.AttachmentGUID = guid;
info.AddTime = DateTime.Now;
info.Editor = CurrentUser.Name;//登錄人
result = BLLFactory<FileUpload>.Instance.Upload(info);
if (!result.Success)
{
LogTextHelper.Error("上傳文件失敗:" + result.ErrorMessage);
}
}
#endregion
}
catch (Exception ex)
{
result.ErrorMessage = ex.Message;
LogTextHelper.Error(ex);
}
}
}
else
{
result.ErrorMessage = "fileData對(duì)象為空";
}
return ToJsonContent(result);
}
文件上傳處理后,返回一個(gè)通用的CommonResult 的結(jié)果對(duì)象,也方便我們?cè)贘S客戶端進(jìn)行判斷處理。
而其中檢查我們導(dǎo)入Excel的數(shù)據(jù)是否滿足列要求的處理,就是判斷它的數(shù)據(jù)列和我們預(yù)先設(shè)置好的列名是否一致即可。
//導(dǎo)入或?qū)С龅淖侄瘟斜?
string columnString = "姓名,手機(jī),郵箱,主頁,興趣愛好,性別,年齡,出生日期,身高,備注";
/// <summary>
/// 檢查Excel文件的字段是否包含了必須的字段
/// </summary>
/// <param name="guid">附件的GUID</param>
/// <returns></returns>
public ActionResult CheckExcelColumns(string guid)
{
CommonResult result = new CommonResult();
try
{
DataTable dt = ConvertExcelFileToTable(guid);
if (dt != null)
{
//檢查列表是否包含必須的字段
result.Success = DataTableHelper.ContainAllColumns(dt, columnString);
}
}
catch (Exception ex)
{
LogTextHelper.Error(ex);
result.ErrorMessage = ex.Message;
}
return ToJsonContent(result);
}
而GetExcelData則是格式化Excel數(shù)據(jù)到具體的List<TestUserInfo>集合里面,這樣我們方便在客戶端進(jìn)行各種屬性的操作,它的代碼如下所示。
/// <summary>
/// 獲取服務(wù)器上的Excel文件,并把它轉(zhuǎn)換為實(shí)體列表返回給客戶端
/// </summary>
/// <param name="guid">附件的GUID</param>
/// <returns></returns>
public ActionResult GetExcelData(string guid)
{
if (string.IsNullOrEmpty(guid))
{
return null;
}
List<TestUserInfo> list = new List<TestUserInfo>();
DataTable table = ConvertExcelFileToTable(guid);
if (table != null)
{
#region 數(shù)據(jù)轉(zhuǎn)換
int i = 1;
foreach (DataRow dr in table.Rows)
{
bool converted = false;
DateTime dtDefault = Convert.ToDateTime("1900-01-01");
DateTime dt;
TestUserInfo info = new TestUserInfo();
info.Name = dr["姓名"].ToString();
info.Mobile = dr["手機(jī)"].ToString();
info.Email = dr["郵箱"].ToString();
info.Homepage = dr["主頁"].ToString();
info.Hobby = dr["興趣愛好"].ToString();
info.Gender = dr["性別"].ToString();
info.Age = dr["年齡"].ToString().ToInt32();
converted = DateTime.TryParse(dr["出生日期"].ToString(), out dt);
if (converted && dt > dtDefault)
{
info.BirthDate = dt;
}
info.Height = dr["身高"].ToString().ToDecimal();
info.Note = dr["備注"].ToString();
info.Creator = CurrentUser.ID.ToString();
info.CreateTime = DateTime.Now;
info.Editor = CurrentUser.ID.ToString();
info.EditTime = DateTime.Now;
list.Add(info);
}
#endregion
}
var result = new { total = list.Count, rows = list };
return ToJsonContent(result);
}
另一個(gè)SaveExcelData的函數(shù)就是處理數(shù)據(jù)導(dǎo)入的最終處理函數(shù),主要就是把集合寫入到具體的數(shù)據(jù)庫里面即可,具體代碼如下所示。
/// <summary>
/// 保存客戶端上傳的相關(guān)數(shù)據(jù)列表
/// </summary>
/// <param name="list">數(shù)據(jù)列表</param>
/// <returns></returns>
public ActionResult SaveExcelData(List<TestUserInfo> list)
{
CommonResult result = new CommonResult();
if (list != null && list.Count > 0)
{
#region 采用事務(wù)進(jìn)行數(shù)據(jù)提交
DbTransaction trans = BLLFactory<TestUser>.Instance.CreateTransaction();
if (trans != null)
{
try
{
//int seq = 1;
foreach (TestUserInfo detail in list)
{
//detail.Seq = seq++;//增加1
detail.CreateTime = DateTime.Now;
detail.Creator = CurrentUser.ID.ToString();
detail.Editor = CurrentUser.ID.ToString();
detail.EditTime = DateTime.Now;
BLLFactory<TestUser>.Instance.Insert(detail, trans);
}
trans.Commit();
result.Success = true;
}
catch (Exception ex)
{
LogTextHelper.Error(ex);
result.ErrorMessage = ex.Message;
trans.Rollback();
}
}
#endregion
}
else
{
result.ErrorMessage = "導(dǎo)入信息不能為空";
}
return ToJsonContent(result);
}
上面這幾個(gè)函數(shù)的代碼一般是比較有規(guī)律的,不需要一個(gè)個(gè)去編寫,一般通過代碼生成工具Database2Sharp批量生成即可。這樣可以有效提高Web的界面代碼和后臺(tái)代碼的開發(fā)效率,減少出錯(cuò)的機(jī)會(huì)。
整個(gè)導(dǎo)入Excel數(shù)據(jù)的處理過程,所有代碼都貼出來了,基本上整個(gè)邏輯了解了就可以很好的了解這個(gè)過程的代碼了。