My MVC3 Summary


1.添加Uploadify控件的相關文件

2.在要用到控件的視圖里添加引用

3.JS代碼

View Code
 1  $(document).ready(function () {
2 //上傳
3 $('#file_upload').uploadify({
4 'uploader': '/Scripts/upload/uploadify.swf', //按鈕
5 'script': '/upload/img?immediate=1',//處理方法(控制器)
6 'cancelImg': '/Scripts/upload/cancel.png',//取消
7 'folder': '/upload',//上傳到文件夾(自己創建)
8 'fileExt': '*.jpg;*.gif;*.png',//格式
9 'fileDesc': 'Image Files (.JPG, .GIF, .PNG)',//描述
10 'removeCompleted': true,
11 'sizeLimit': 102400 * 10,//大小限制
12 'onComplete': resultfun //完成則執行以下方法(自定義)
13 });
14 $("#btnUpload").click(function () {//點擊上傳前要判斷
15 if (checkImport()) {//執行判斷的方法(自定義)
16 $('#file_upload').uploadifyUpload();//執行上傳
17 }
18 });
19 });
20 function resultfun(event, queueID, fileObj, response, data) {
21 if (response != "") {
22 var dd = eval("(" + response + ")"); //轉換
23 if (dd.msg.err == undefined) {
24 var imgsul = dd.msg.url.replace("!", "")
25 // $("#image_url").val(imgsul);
26 $("#imgDiv").attr("src", imgsul);//實現預覽效果
27 // $("#result").html("圖片上傳成功!");
28 alert("成功上傳!");
29 }
30 }
31 else {
32 alert("圖片上傳出錯!");
33 }
34 }
35 function checkImport() {
36 if ($.trim($('#file_uploadQueue').html()) == "") {
37 alert('請先選擇要上傳的的文件!');
38 return false;
39 }
40 return true;
41 }

4.處理方法(控制器)

View Code
  1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.Mvc;
6 using System.Text.RegularExpressions;
7 using System.IO; //一定要應用IO命名空間
8
9 namespace webcourse.Controllers
10 {
11 public class UploadController : Controller
12 {
13 //控制器名稱:Img
14 // GET: /Upload/
15
16 [HttpPost]//post 方式
17 public ActionResult Img(HttpPostedFileBase fileData)//傳參
18 {
19 Response.Charset = "UTF-8";
20 // 初始化一大堆變量
21 //string inputname = "filedata";//表單文件域name
22 string attachdir = "/upload";// 上傳文件保存路徑,結尾不要帶/
23 int dirtype = 1; // 1:按天存入目錄 2:按月存入目錄 3:按擴展名存目錄 建議使用按天存
24 int maxattachsize = 2097152; // 最大上傳大小,默認是2M
25 string upext = "txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid"; // 上傳擴展名
26 int msgtype = 2; //返回上傳參數的格式:1,只返回url,2,返回參數數組
27 string immediate = Request.QueryString["immediate"];//立即上傳模式,僅為演示用
28 byte[] file; // 統一轉換為byte數組處理
29 string localname = "";
30 string disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];
31
32 string err = "";
33 string msg = "''";
34
35 if (disposition != null)
36 {
37 // HTML5上傳
38 file = Request.BinaryRead(Request.TotalBytes);
39 localname = Server.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value);// 讀取原始文件名
40 }
41 else
42 {
43 //HttpFileCollectionBase filecollection = Request.Files;
44 //HttpPostedFileBase fileData = filecollection.Get(inputname);
45
46 // 讀取原始文件名
47 localname = fileData.FileName;
48 // 初始化byte長度.
49 file = new Byte[fileData.ContentLength];
50
51 // 轉換為byte類型
52 System.IO.Stream stream = fileData.InputStream;
53 stream.Read(file, 0, fileData.ContentLength);
54 stream.Close();
55
56 //filecollection = null;
57 }
58 //if (Session["UserID"] == null) err = "登錄超時,請登錄后重試!";
59 //else
60 //{
61 if (file.Length == 0) err = "無數據提交";
62 else
63 {
64 if (file.Length > maxattachsize) err = "文件大小超過" + maxattachsize + "字節";
65 else
66 {
67 string attach_dir, attach_subdir, filename, extension, target;
68
69 // 取上載文件后綴名
70 extension = GetFileExt(localname);
71
72 if (("," + upext + ",").IndexOf("," + extension + ",") < 0) err = "上傳文件擴展名必需為:" + upext;
73 else
74 {
75 switch (dirtype)
76 {
77 case 2:
78 attach_subdir = "month_" + DateTime.Now.ToString("yyMM");
79 break;
80 case 3:
81 attach_subdir = "ext_" + extension;
82 break;
83 default:
84 attach_subdir = "day_" + DateTime.Now.ToString("yyMMdd");
85 break;
86 }
87 attach_dir = attachdir + "/" + attach_subdir + "/";
88
89 // 生成隨機文件名
90 Random random = new Random(DateTime.Now.Millisecond);
91 filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension;
92
93 target = attach_dir + filename;
94 try
95 {
96 CreateFolder(Server.MapPath("~/" + attach_dir));
97
98 System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/" + target), System.IO.FileMode.Create, System.IO.FileAccess.Write);
99 fs.Write(file, 0, file.Length);
100 fs.Flush();
101 fs.Close();
102 }
103 catch (Exception ex)
104 {
105 err = ex.Message.ToString();
106 }
107
108 // 立即模式判斷
109 if (immediate == "1") target = "!" + target;
110 target = jsonString(target);
111 if (msgtype == 1) msg = "'" + target + "'";
112 else msg = "{'url':'" + target + "','localname':'" + jsonString(localname) + "','id':'1'}";
113 }
114 }
115 }
116 file = null;
117 //}
118
119
120 //Response.Write("{'err':'" + jsonString(err) + "','msg':" + msg + "}");
121 return this.Content("{'err':'" + jsonString(err) + "','msg':" + msg + "}");
122 }
123
124
125 string jsonString(string str)
126 {
127 str = str.Replace("\\", "\\\\");
128 str = str.Replace("/", "\\/");
129 str = str.Replace("'", "\\'");
130 return str;
131 }
132
133
134 string GetFileExt(string FullPath)
135 {
136 if (FullPath != "") return FullPath.Substring(FullPath.LastIndexOf('.') + 1).ToLower();
137 else return "";
138 }
139 //創建文件夾
140 void CreateFolder(string FolderPath)
141 {
142 if (!System.IO.Directory.Exists(FolderPath)) System.IO.Directory.CreateDirectory(FolderPath);
143 }
144 [AcceptVerbs(HttpVerbs.Post)]
145 public ContentResult Import(HttpPostedFileBase FileData, string folder, string name)
146 {
147 string result = "";
148 if (null != FileData)
149 {
150 try
151 {
152 string extension = Path.GetExtension(FileData.FileName).ToLower();//獲得文件擴展名
153 // 生成隨機文件名
154 Random random = new Random(DateTime.Now.Millisecond);
155 string filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension;
156
157 saveFile(FileData, filename);//保存文件
158 }
159 catch
160 {
161 result = "";
162 }
163 }
164 return Content(result);
165 }
166 [NonAction]
167 private void saveFile(HttpPostedFileBase postedFile, string saveName)
168 {
169 string phyPath = Request.MapPath("~/upload/img/");
170 if (!Directory.Exists(phyPath))
171 {
172 Directory.CreateDirectory(phyPath);
173 }
174 try
175 {
176 postedFile.SaveAs(phyPath + saveName);
177 }
178 catch (Exception e)
179 {
180 throw new ApplicationException(e.Message);
181 }
182 }
183
184 }
185 }

5.效果




免責聲明!

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



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