MVC ajaxfileupload 实现无刷新导入或上传功能

直接上代码吧

前台

先引用 ajaxfileupload.js

<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 控件

 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         }

 

posted @ 2017-09-08 17:19  老-顾  阅读(2232)  评论(0编辑  收藏  举报