My MVC3 Summary Uploadify控件
1.添加Uploadify控件的相关文件
2.在要用到控件的视图里添加引用
3.JS代码
View Code1 $(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 Code1 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.效果
TAG:MVC3 图片/文件 上传