C# 文件上傳(能夠多文件上傳)

1、前端搭建

       一、前端用到js:uploadify(下載地址:http://www.uploadify.com/download/)、layer (下載地址:http://layer.layui.com/),下載以後把它們放在你的項目裏 列如javascript

    

  二、根據你的須要在你項目適當的位置創建上傳文件的目錄  列如(File)css

         

       到此前端搭建結束前端

2、配置文件修改(可選擇跳過此步驟)

  一、首先說明下,這個步驟能夠跳過,此步驟主要是修改上傳文件大小的限制(.net 默認最大隻能上傳4M)如若須要修改請繼續閱讀該步驟。java

  二、打開web.config 配置文件 找到<system.web> 節點 ,在該節點下面添加以下節點jquery

        <httpRuntime targetFramework="4.5"   executionTimeout="500" maxRequestLength="409600" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" />web

       <!-- maxRequestLength屬性是上傳文件大小的設置 值是kb大小  maxRequestLength=「1024」  爲最大上傳1M  -->後端

3、代碼編寫

  一、說明下:我用的是mvc模式 因此這裏就用mvc的方式編寫 (代碼是不變的,開發者能夠根據大家的設計模式編寫)設計模式

  二、創建一個控制器PageBaseController在該控制器裏編寫以下代碼 (若是是用的aspx頁面那麼把FileUpdateView方法刪掉  ,把UploadifyFile 方法的ActionResult改爲void  並去掉return null;) 安全

   後端代碼以下 mvc

 1         /// <summary>
 2         /// 文件上傳頁面
 3         /// </summary>
 4         /// <returns></returns>
 5         public ActionResult FileUpdateView()
 6         {
 7             return View();
 8         }
 9 
10         /// <summary>
11         /// 文件處理方法
12         /// </summary>
13         /// <param name="filedata"></param>
14         /// <returns></returns>
15         public ActionResult UploadifyFile(HttpPostedFileBase filedata)
16         {
17             if (filedata == null ||
18                 String.IsNullOrEmpty(filedata.FileName) ||
19                 filedata.ContentLength == 0)
20             {
21                 return HttpNotFound();
22             }
23 
24             string filename = System.IO.Path.GetFileName(filedata.FileName);
25             string virtualPath = String.Format("~/File/{0}", filename);
26 
27             string path = Server.MapPath(virtualPath);
28             // 如下注釋的代碼 均可以得到文件屬性
29            // System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(path);
30             // FileInfo file = new FileInfo(filedata.FileName);
31 
32             filedata.SaveAs(path);
33             return null;
34         }      
View Code

     注:virtualPath 是咱們搭建上傳文件的目錄

  三、在視圖(頁面)裏引用咱們搭建的js:uploadfiy 、layer 路徑 

          列如:       

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/lib/layer/layer.js"></script>
<link href="~/Scripts/lib/uploadify/uploadify.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/lib/uploadify/jquery.uploadify.min.js"></script>

         注:這裏咱們用到了jquery

  四、前端代碼

 1 <script type="text/javascript">
 2     var uploadifyOnSelectError;
 3     var uploadifyOnUploadError;
 4     var uploadifyOnSelect;
 5     var uploadifyOnUploadSuccess;
 6     uploadifyOnSelectError = function (file, errorCode, errorMsg) {
 7         var msgText = "上傳失敗\n";
 8         switch (errorCode) {
 9             case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
10                 //this.queueData.errorMsg = "每次最多上傳 " + this.settings.queueSizeLimit + "個文件";
11                 msgText += "每次最多上傳 " + this.settings.queueSizeLimit + "個文件";
12                 break;
13             case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
14                 msgText += "文件大小超過限制( " + this.settings.fileSizeLimit + " )";
15                 break;
16             case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
17                 msgText += "文件大小爲0";
18                 break;
19             case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
20                 msgText += "文件格式不正確,僅限 " + this.settings.fileTypeExts;
21                 break;
22             default:
23                 msgText += "錯誤代碼:" + errorCode + "\n" + errorMsg;
24         }
25         layer.msg(msgText);
26     };
27     uploadifyOnUploadError = function (file, errorCode, errorMsg, errorString) {
28         // 手工取消不彈出提示
29         if (errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED
30             || errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {
31             return;
32         }
33         var msgText = "上傳失敗\n";
34         switch (errorCode) {
35             case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
36                 msgText += "HTTP 錯誤\n" + errorMsg;
37                 break;
38             case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
39                 msgText += "上傳文件丟失,請從新上傳";
40                 break;
41             case SWFUpload.UPLOAD_ERROR.IO_ERROR:
42                 msgText += "IO錯誤";
43                 break;
44             case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
45                 msgText += "安全性錯誤\n" + errorMsg;
46                 break;
47             case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
48                 msgText += "每次最多上傳 " + this.settings.uploadLimit + "";
49                 break;
50             case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
51                 msgText += errorMsg;
52                 break;
53             case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
54                 msgText += "找不到指定文件,請從新操做";
55                 break;
56             case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
57                 msgText += "參數錯誤";
58                 break;
59             default:
60                 msgText += "文件:" + file.name + "\n錯誤碼:" + errorCode + "\n"
61                     + errorMsg + "\n" + errorString;
62         }
63         layer.msg(msgText);
64     };
65 
66     uploadifyOnSelect = function () {
67     };
68     uploadifyOnUploadSuccess = function (file, data, response) {
69         layer.msg(file.name + "\n\n" + response + "\n\n" + data);
70     };
71     $(function () {
72 
73         $("#uploadify").uploadify({
74             uploader: '/PageBase/UploadifyFun', //處理上傳的方法
75             swf: '/Scripts/lib/uploadify/uploadify.swf',
76             width: 80, // 按鈕寬度
77             height: 60, //按鈕高度
78             buttonText: "上傳文件",
79             buttonCursor: 'hand',
80             fileSizeLimit:20480,
81             fileobjName: 'Filedata',
82             fileTypeExts: '*.xlsx;*.docx', //擴展名
83             fileTypeDesc: "請選擇xslx,docx文件", //文件說明
84             auto: false, //是否自動上傳
85             multi: true, //是否一次能夠選中多個文件
86             queueSizeLimit: 5, //容許同時上傳文件的個數
87             overrideEvents: ['onSelectError', 'onDialogClose'],  // 是否要默認提示  要就不配置
88             onSelect: uploadifyOnSelect,
89             onSelectError: uploadifyOnSelectError,
90             onUploadError: uploadifyOnUploadError,
91             onUploadSuccess: uploadifyOnUploadSuccess
92         });
93     });
94 </script>
95 <span id="uploadify"></span>
96 <div>
97     <a href="javascript:$('#uploadify').uploadify('upload','*');">上傳</a>
98     <a href="javascript:$('#uploadify').uploadify('cancel', '*');">取消</a>
99 </div>
View Code

   注:fileSizeLimit 屬性的值最好和咱們web.config 裏設置的文件上傳最大值同樣(不能大於這個值)

   到這裏。咱們文件上傳就結束了。

   喜歡個人文章就關注我吧,有疑問能夠留言。

相關文章
相關標籤/搜索