開發環境:WIN10+IE11,瀏覽器請使用IE10或以上版本
開發技術框架MVC4+JQuery Easyui+knockoutjs
效果為彈出小窗體,如下圖

1.前端cshtml文件代碼(只包含文件上傳窗體)。注意form設置,必須使用form-data傳遞文件。注意按鈕事件我這里是封裝的data-bind="click:closeImportClick",不要照抄
html5可直接在input標簽file控件中設置accept屬性限制上傳文件類型,設置multiple屬性可同時上傳多個文件
<div class="easyui-window" id="import-excel-template" title="文件上傳" style="width:400px;height:160px;padding:2px;" closed="true"> <form id="importFileForm" method="post" enctype="multipart/form-data" style="display:none"> <table style="margin:5px;height:70px;"> <tr> <td>請選擇文件</td> <td width="5px;"></td> <td><input type="file" class="easyui-filebox" id="fileImport" name="fileImport" style="width:260px;"></td> <td></td></tr> <tr> <td colspan="4"><label id="fileName" /></td> </tr> <tr> <td colspan="4"> <label id="uploadInfo" /> </td> </tr> </table><div style="text-align:center;clear:both;margin:5px;"> <a id="uploadFile" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" data-bind="click:importFileClick" href="javascript:void(0)">上傳</a> <a class="easyui-linkbutton" data-options="iconCls:'icon-cancel'" data-bind="click:closeImportClick" href="javascript:void(0)">關閉</a> </div> </form> </div>
2.ViewModel中js代碼:定義上傳事件。注意使用ajax請求時,需要設置contentType: false,否則chrome和firefox不兼容
//導入事件,顯示導入彈出窗口 this.importClick = function () {
$('#import-excel-template').window('open')
document.getElementById("importFileForm").style.display = "block"; } //關閉導入彈出窗口 this.closeImportClick = function () { document.getElementById('fileImport').value = null; document.getElementById('fileName').innerHTML = ""; document.getElementById('uploadInfo').innerHTML = ""; $('#import-excel-template').window('close') } //導入文件 this.importFileClick = function () { //獲取上傳文件控件內容 var file = document.getElementById('fileImport').files[0]; //判斷控件中是否存在文件內容,如果不存在,彈出提示信息,阻止進一步操作 if (file == null) { alert('錯誤,請選擇文件'); return; } //獲取文件名稱 var fileName = file.name; //獲取文件類型名稱 var file_typename = fileName.substring(fileName.lastIndexOf('.'), fileName.length); //這里限定上傳文件文件類型必須為.xlsx,如果文件類型不符,提示錯誤信息 if (file_typename == '.xlsx') { //計算文件大小 var fileSize = 0; //如果文件大小大於1024字節X1024字節,則顯示文件大小單位為MB,否則為KB if (file.size > 1024 * 1024) {
fileSize = Math.round(file.size * 100 / (1024 * 1024)) / 100;
if (fileSize > 10) { alert('錯誤,文件超過10MB,禁止上傳!'); return; }
fileSize = fileSize.toString() + 'MB'; } else { fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'; } //將文件名和文件大小顯示在前端label文本中 document.getElementById('fileName').innerHTML = "<span style='color:Blue'>文件名: " + file.name + ',大小: ' + fileSize + "</span>"; //獲取form數據 var formData = new FormData($("#importFileForm")[0]); //調用apicontroller后台action方法,將form數據傳遞給后台處理。contentType必須設置為false,否則chrome和firefox不兼容 $.ajax({ url: "/api/Product/NewMaterialImport/PostExcelData", type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (returnInfo) { //上傳成功后將控件內容清空,並顯示上傳成功信息 document.getElementById('fileImport').value = null; document.getElementById('uploadInfo').innerHTML = "<span style='color:Red'>" + returnInfo + "</span>"; }, error: function (returnInfo) { //上傳失敗時顯示上傳失敗信息 document.getElementById('uploadInfo').innerHTML = "<span style='color:Red'>" + returnInfo + "</span>"; } }); } else { alert("文件類型錯誤"); //將錯誤信息顯示在前端label文本中 document.getElementById('fileName').innerHTML = "<span style='color:Red'>錯誤提示:上傳文件應該是.xlsx后綴而不應該是" + file_typename + ",請重新選擇文件</span>" } }
3.apicontroller代碼
/// <summary> /// 將文件上傳到指定路徑中保存 /// </summary> /// <returns>上傳文件結果信息</returns> [System.Web.Http.HttpPost] [ValidateInput(false)] public string PostExcelData() { string info = string.Empty; try { //獲取客戶端上傳的文件集合 HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; //判斷是否存在文件 if (files.Count > 0) { //獲取文件集合中的第一個文件(每次只上傳一個文件) HttpPostedFile file = files[0]; //定義文件存放的目標路徑 string targetDir = System.Web.HttpContext.Current.Server.MapPath("~/FileUpLoad/Product"); //創建目標路徑 ZFiles.CreateDirectory(targetDir); //組合成文件的完整路徑 string path = System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file.FileName)); //保存上傳的文件到指定路徑中 file.SaveAs(path); info = "上傳成功"; } else { info = "上傳失敗"; } } catch { info= "上傳失敗"; } return info; }
