直接上代碼吧javascript
前臺java
先引用 ajaxfileupload.jsajax
<script src="~/Scripts/ajaxfileupload.js"></script>
1 <input type="file" id="test_file" name="test_file" style="display:none" /> 2 3 <a href="#" id="test_ImportData">導入數據</a>
這麼作是爲了避免讓那個醜的要死的file 控件出來 直接用一個按鈕觸發 隱藏掉原來的file 控件json
1 <script type="text/javascript"> 2 (function () { 3 var changefile = function () { 4 var ajaxDialog = ShowWaitMessageDialog("");//遮罩層 5 $.ajaxFileUpload({ 6 url: '/Home/Import',//須要連接到服務器地址 7 secureuri: false, 8 fileElementId: 'test_file',//文件選擇框的id屬性 9 dataType: 'text', //服務器返回的格式,能夠是json 可是不兼容IE 故改成Text 10 success: function (data, status) { 11 //返回以後的操做 12 //... 13 HideWaitMessageDialog(ajaxDialog);//關閉提交時的彈層提示 14 }, 15 complete: function (xmlHttpRequest) { 16 //解決點擊一次file失效 17 $("#test_file").replaceWith('<input type="file" id="test_file" name="test_file" style="display:none"/>'); 18 $("#test_file").change(function () { 19 changefile(); 20 }); 21 }, 22 error: function (data, status, e) { 23 HideWaitMessageDialog(ajaxDialog);//關閉提交時的彈層提示 24 alert(e); 25 } 26 }); 27 }; 28 $("#test_ImportData").click(function () { 29 $("#test_file").click(); 30 }); 31 $("#test_file").change(function () { 32 changefile(); 33 }); 34 }()); 35 </script>
而後是後臺接收,接收完後我是先把他存到本地,而後取出來服務器
1 public string Import() 2 { 3 try 4 { 5 HttpFileCollection httpFileCollection = System.Web.HttpContext.Current.Request.Files; 6 string path = ""; 7 DataTable dt = null; 8 if (httpFileCollection.Count > 0) 9 { 10 string fileName = httpFileCollection[0].FileName; 11 if (fileName.IndexOf("\\") > -1) 12 { 13 //IE的狀況 14 fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1); 15 } 16 path = "/UploadFiles/" + fileName; 17 string PhysicalPath = Server.MapPath(path); 18 httpFileCollection[0].SaveAs(PhysicalPath);//存到項目文件中, 19 dt = ExcelUtil.ReadFromCSV(PhysicalPath, true);// 經過路徑讀取文件內容存到datatable中 20 21 } 22 return JsonUtil.SerializeObject(dt); 23 } 24 catch (Exception ex) 25 { 26 throw ex; 27 } 28 }