C# 文件上傳(可以多文件上傳)


一、前端搭建

       1、前端用到js:uploadify(下載地址:http://www.uploadify.com/download/)、layer (下載地址:http://layer.layui.com/),下載之后把它們放在你的項目里 列如

    

  2、根據你的需要在你項目適當的位置建立上傳文件的目錄  列如(File)

         

       到此前端搭建結束

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

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

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

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

       <!-- maxRequestLength屬性是上傳文件大小的設置 值是kb大小  maxRequestLength=“1024”  為最大上傳1M  -->

三、代碼編寫

  1、說明下:我用的是mvc模式 所以這里就用mvc的方式編寫 (代碼是不變的,開發者可以根據你們的設計模式編寫)

  2、建立一個控制器PageBaseController在該控制器里編寫如下代碼 (如果是用的aspx頁面那么把FileUpdateView方法刪掉  ,把UploadifyFile 方法的ActionResult改成void  並去掉return null;) 

   后端代碼如下 

 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 是我們搭建上傳文件的目錄

  3、在視圖(頁面)里引用我們搭建的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

  4、前端代碼

 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 里設置的文件上傳最大值一樣(不能大於這個值)

   到這里。我們文件上傳就結束了。

   喜歡我的文章就關注我吧,有疑問可以留言。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM