一周杂记(MVC 图片上传)
前两周在外校的校园招聘会被一家国内的大软件公司录用,算是对我大学期间自学编程的一个的答卷,目前在一家小公司做一个石油公司MVC项目,是基于现成的框架做的,没什么技术含量,公司后台甚至不让用Jquery,用的是MVC2,M设计的也有问题,提示只让用alter,页面树不是递归只是分层,没办法,老板说什么我就怎么做,刚去的时候老板说要培训下,结果一去就是做项目,而且两个人做一个20多万的项目,刚去的时候无压力,中间压力大,现在麻木了,大四独自走出学校才发现我好想 好好地坐在教室听听老师的课,可是想想老师门那无聊的空洞而不实际的屁话,弄得我们的同学们没一点竞争力,大四居然为签工作发愁,我又不想回去了,只是偶然回去交个作业,其实作为一个广告学的学生,我没有学到多少专业的知识,多少有点遗憾,大学的四年,但是除了教材陈旧,研究的广告都是非广告专业的人做出来的经典案例,老师的不负责,一个百度,优酷上的广告短片几个不同科目的老师貌似都喜欢复制拿过来十遍八遍的放,为什么不想着我们怎么去创造自己的广告,而去神话别人的案例,这学期老师在教网页设计给大家讲什么前后台,如果你看到,你就会对中国的二本大学的老师糊弄学生的本领彻底折服,老师却认为自己很牛逼在学生面前装的一本正经,以为学广告的学生什么都不懂,拿着点HTML皮毛讲一学期(其实即使没有基础的人30分钟都绝对全部学完了)。无论怎么样,祝福我的母校振作起来,垃圾的老师都滚出去,不在毁人不倦,也祝愿我专业的同学们找到自己喜欢的公司和事业。
现在给同学们演示一个上传图片的示例:
--- 功能上传图片,自动生成两种大小的图片,由于图片服务器一般都是独立的,所以我们这里也是做一个独立的Web网站来模拟
主要代码如下:
<%@ WebHandler Language="C#" Class="Pic_Upload" %> using System; using System.Web; using System.IO; using System.Web.Services; using System.Drawing.Imaging; using System.Drawing; public class Pic_Upload : IHttpHandler { private int q_big = 100, q_small = 80;//清晰度 private int w_big = 360, h_big = 265; private int w_small = 150, h_small = 100; private int fontSize = 20;//水印字体大小 private string content = "钓鱼岛是中国的";//水印文字 private HttpContext _context; private string host = ""; public void ProcessRequest(HttpContext context) { host = context.Request.Url.Host; if (CheckRequest()) { _context = context; string fileName = context.Request.Form["fileName"]; if (string.IsNullOrEmpty(fileName)) { ResponseWrite(""); return; } string big_width = context.Request.Form["big_width"]; string big_height = context.Request.Form["big_height"]; string small_width = context.Request.Form["small_width"]; string small_height = context.Request.Form["small_height"]; int.TryParse(big_width, out w_big); int.TryParse(big_height, out h_big); int.TryParse(small_width, out w_small); int.TryParse(small_height, out h_small); context.Response.ContentType = "text/plain"; string content = context.Request.Form["data"]; string path = context.Request.Form["path"]; Upload(fileName, content, path); ResponseWrite(string.Format("http://" + host + "/UpPhotos/{0}/", path.Replace("\\", "/")));//返回图片保存路径 } else { _context = context; ResponseWrite(""); } } private bool CheckRequest() { //if (host == "localhost") //{ // host += ":49191"; return true; //} //return host.IndexOf("910jq") >= 0; return true; } /// <summary> /// 上传类 /// </summary> /// <param name="ext"></param> /// <param name="content"></param> private void Upload(string fileName, string content, string path) { string currentPath = HttpContext.Current.Request.PhysicalApplicationPath + "UpPhotos\\" + path + "\\"; if (!Directory.Exists(currentPath)) { Directory.CreateDirectory(currentPath); } //从文件获取原始图片,并使用流中嵌入的颜色管理信息 byte[] buffer = Convert.FromBase64String(content); System.Drawing.Image initImage = ByteToImg(buffer); //保存大图片 string fileNameBig = fileName + ".jpg"; string fullBigPath = currentPath + fileNameBig; ForTemplate(initImage, fullBigPath, w_big, h_big, q_big, "jpeg"); //保存小图片 string fileNameSmall = fileName + "_small" + ".jpg"; string fullSmallPath = currentPath + fileNameSmall; ForTemplate(initImage, fullSmallPath, w_small, h_small, q_small, "jpeg"); initImage.Dispose(); } /// <summary> /// 上传类 /// </summary> /// <param name="ext"></param> /// <param name="content"></param> private void UploadLogo(string fileName, string content, string path) { string currentPath = HttpContext.Current.Request.PhysicalApplicationPath + "UpPhotos\\" + path + "\\"; if (!Directory.Exists(currentPath)) { Directory.CreateDirectory(currentPath); } //从文件获取原始图片,并使用流中嵌入的颜色管理信息 byte[] buffer = Convert.FromBase64String(content); System.Drawing.Image initImage = ByteToImg(buffer); //保存小图片 string fileNameSmall = fileName + "_small" + ".gif"; string fullSmallPath = currentPath + fileNameSmall; ForTemplate(initImage, fullSmallPath, w_small, h_small, q_small, "gif"); initImage.Dispose(); } /// <summary> /// 生成http内容 /// </summary> /// <param name="content"></param> private void ResponseWrite(string content) { _context.Response.ClearContent(); _context.Response.ContentType = "text/plain"; _context.Response.Write(content); _context.Response.End(); } private void ForTemplate(Image initImage, string fileSaveUrl, int maxWidth, int maxHeight, int quality, string imageType) { //按模板生成 System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight); System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage); templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; templateG.Clear(Color.Transparent); templateG.DrawImage(initImage, new Rectangle(0, 0, maxWidth, maxHeight), new Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel); //增加水印 System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, maxWidth, maxHeight), Color.Silver, Color.Silver, 1.2f, true); Font fontWater = new Font("Arial", fontSize, FontStyle.Bold); SizeF siF = templateG.MeasureString(content, fontWater); templateG.DrawString(content, fontWater, brush, maxWidth - (siF.Width + 5), maxHeight - (siF.Height + 5)); using (EncoderParameters parms = new EncoderParameters(1)) { parms.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); templateImage.Save(fileSaveUrl, GetImageEncoder(imageType), parms); } templateImage.Dispose(); } private ImageCodecInfo GetImageEncoder(string imageType) { imageType = imageType.ToUpperInvariant(); foreach (ImageCodecInfo info in ImageCodecInfo.GetImageEncoders()) { if (info.FormatDescription.ToLower().Contains(imageType.ToLower())) { return info; } } return null; } /// <summary> /// 字节流转换成图片 /// </summary> /// <param name="byt">要转换的字节流</param> /// <returns>转换得到的Image对象</returns> private Image ByteToImg(byte[] byt) { MemoryStream ms = new MemoryStream(byt); Image img = Image.FromStream(ms); return img; } public bool IsReusable { get { return false; } } }
----现在我们来实现上传操作
步骤一.新建项目----》ASP.NET MVC3 WEB应用程序----》选择Internet应用程序(这个无所谓只是为了节省时间)
步骤二:在View---》Home----》Index(也是为了节约演示时间),添加上传代码,这里我们使用ajax方式提交
@{ ViewBag.Title = "主页"; } <h2>@ViewBag.Message</h2> <p> <script src="http://www.cnblogs.com/Scripts/ajaxfileupload.js"></script> <script type="text/javascript"> function Upload() { $.ajaxFileUpload({ url: 'Home/Photo_Save', secureuri: false, fileElementId: 'pic_upload', dataType: 'Json', data: {}, success: function(data, status) { var args = data.split("|"); if (args[0] == "1") { alert(args[1]); } else { alert("上传失败!"); } }, error: function(data, status, e) { alert(e); } }); } </script> 若要了解有关 ASP.NET MVC 的更多信息,请访问 <a href="http://asp.net/mvc" title="ASP.NET MVC 网站">http://asp.net/mvc</a>。 logo 图标:<input id="pic_upload" type="file" name="pic_upload" /><input id="upload" type="button" value="上传图片..." onclick="Upload()"/> </p>
HomeController中如下定义:
public ActionResult Photo_Save(HttpPostedFileBase pic_upload) { string serverUrl = "http://localhost:1156"; string logoUrl = serverUrl + "/Image/"; string filePath = "Image"; string logoId = Guid.NewGuid().ToString(); if (pic_upload != null) { string fileType = pic_upload.ContentType; Stream stream = pic_upload.InputStream; BinaryReader br = new BinaryReader(stream); byte[] fileByte = br.ReadBytes((int)stream.Length); string baseFileString = Convert.ToBase64String(fileByte); logoUrl = GetUploadImgUrl(baseFileString, serverUrl, logoId, filePath); if (string.IsNullOrEmpty(logoUrl)) { return Content("0|网络繁忙,请稍后在试!"); } } string imgPath = "http://http://localhost:1156/Image/" + logoId + ".jpg"; return Content("1|上传成功!|" + imgPath); } /// <summary> /// 上传图片 /// </summary> /// <param name="imgString">base64编码过的二进制图片</param> /// <returns></returns> public static string GetUploadImgUrl(string imgString, string serverUrl, string fileName, string path) { //按类型设置图片大小 int big_width = 360; int big_height = 265; int small_width = 150; int small_height = 100; string result = string.Empty; try { string postData = string.Format("clientKey={0}&data={1}&fileName={2}&path={3}&big_width={4}&big_height={5}&small_width={6}&small_height={7}", "www.910jq.com", imgString.Replace("+", "%2B"), fileName, path, big_width, big_height, small_width, small_height); RequestHelper p = new RequestHelper(); result = p.ResponseToString(p.doPost(serverUrl + "/Pic_Upload.ashx", postData)); } catch { result = ""; } return result; }
这里需要一个RequestHelper的辅助类
1 using System; 2 using System.Web; 3 using System.Net; 4 using System.Text; 5 using System.Threading; 6 using System.IO; 7 using System.IO.Compression; 8 namespace LECAD.Common 9 { 10 public class RequestHelper 11 { 12 /// <summary> 13 /// 延迟毫秒数 14 /// </summary> 15 protected int defer; 16 /// <summary> 17 /// 与请求相关的cookie(用于保持session) 18 /// </summary> 19 public CookieContainer cookies = new CookieContainer(); 20 21 public RequestHelper() 22 { 23 this.cookies = new CookieContainer(); 24 //默认为1秒 25 this.defer = 1000; 26 } 27 28 /// <summary> 29 /// 发送Post类型请求 30 /// </summary> 31 /// <param name="url">请求地址</param> 32 /// <param name="postData">参数</param> 33 /// <returns></returns> 34 public WebResponse doPost(string url, string postData) 35 { 36 try 37 { 38 Thread.Sleep(this.defer); 39 byte[] paramByte = Encoding.UTF8.GetBytes(postData); // 转化 40 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); 41 42 webRequest.Method = "POST"; 43 webRequest.ContentType = "application/x-www-form-urlencoded"; 44 //webRequest.Referer = "http://bulo.hjenglish.com/app/app.aspx?aid=1040"; 45 webRequest.Referer = "http://service.910jq.com/Compnay/MenuItemPhoto_Info"; 46 webRequest.KeepAlive = true; 47 webRequest.ProtocolVersion = HttpVersion.Version10; 48 49 50 webRequest.Accept = "application/x-shockwave-flash, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-silverlight, */*"; 51 //webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; CIBA)"; 52 webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)"; 53 54 webRequest.ContentLength = paramByte.Length; 55 webRequest.CookieContainer = this.cookies; 56 webRequest.Timeout = -1; 57 Stream newStream = webRequest.GetRequestStream(); 58 newStream.Write(paramByte, 0, paramByte.Length); //写入参数 59 newStream.Close(); 60 return webRequest.GetResponse(); 61 62 63 64 } 65 catch (Exception ce) 66 { 67 throw ce; 68 } 69 } 70 71 /// <summary> 72 /// 发送Post类型请求 73 /// </summary> 74 /// <param name="url">请求地址</param> 75 /// <param name="postData">参数</param> 76 /// <returns></returns> 77 public WebResponse doPost(string url, string postData, string referer) 78 { 79 try 80 { 81 Thread.Sleep(this.defer); 82 byte[] paramByte = Encoding.UTF8.GetBytes(postData); // 转化 83 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); 84 webRequest.CookieContainer = this.cookies; 85 webRequest.Method = "POST"; 86 webRequest.ContentType = "application/x-www-form-urlencoded"; 87 webRequest.Referer = referer; 88 webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; CIBA)"; 89 webRequest.ContentLength = paramByte.Length; 90 webRequest.Timeout = 5000; 91 Stream newStream = webRequest.GetRequestStream(); 92 newStream.Write(paramByte, 0, paramByte.Length); //写入参数 93 newStream.Close(); 94 return webRequest.GetResponse(); 95 } 96 catch (Exception ce) 97 { 98 throw ce; 99 } 100 } 101 /// <summary> 102 /// 发送Get类型请求 103 /// </summary> 104 /// <param name="url">请求地址</param> 105 /// <param name="postData">参数</param> 106 /// <returns></returns> 107 public WebResponse doGet(string url) 108 { 109 try 110 { 111 //Thread.Sleep(1000); 112 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); 113 webRequest.CookieContainer = this.cookies; 114 webRequest.Method = "get"; 115 webRequest.Timeout = 5000; 116 return webRequest.GetResponse(); 117 } 118 catch (Exception ce) 119 { 120 return null; 121 //throw ce; 122 } 123 } 124 /// <summary> 125 /// 发送Get类型请求 126 /// </summary> 127 /// <param name="url">请求地址</param> 128 /// <param name="postData">参数</param> 129 /// <returns></returns> 130 public WebResponse doGet(string url, string referer) 131 { 132 try 133 { 134 //Thread.Sleep(1000); 135 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); 136 webRequest.CookieContainer = this.cookies; 137 webRequest.Method = "get"; 138 webRequest.Referer = referer; 139 webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; CIBA)"; 140 return webRequest.GetResponse(); 141 } 142 catch (Exception ce) 143 { 144 throw ce; 145 } 146 } 147 /// <summary> 148 /// 根据相应返回字符串 149 /// </summary> 150 /// <param name="response"></param> 151 /// <returns></returns> 152 public string ResponseToString(WebResponse response) 153 { 154 try 155 { 156 Encoding encoding = Encoding.Default; 157 string ContentType = response.ContentType.Trim(); 158 if (ContentType.IndexOf("utf-8") != -1) 159 encoding = Encoding.UTF8; 160 else if (ContentType.IndexOf("utf-7") != -1) 161 encoding = Encoding.UTF7; 162 else if (ContentType.IndexOf("unicode") != -1) 163 encoding = Encoding.Unicode; 164 165 StreamReader stream = new StreamReader(response.GetResponseStream(), encoding); 166 string code = stream.ReadToEnd(); 167 stream.Close(); 168 response.Close(); 169 return code; 170 } 171 catch (Exception ce) 172 { 173 throw ce; 174 } 175 } 176 177 /// <summary> 178 /// 根据相应返回字符串 179 /// </summary> 180 /// <param name="response"></param> 181 /// <returns></returns> 182 public string ResponseToStringWithGzip(WebResponse response) 183 { 184 try 185 { 186 Encoding encoding = Encoding.Default; 187 string ContentType = response.ContentType.Trim().ToLower(); 188 if (ContentType.IndexOf("utf-8") != -1) 189 encoding = Encoding.UTF8; 190 else if (ContentType.IndexOf("utf-7") != -1) 191 encoding = Encoding.UTF7; 192 else if (ContentType.IndexOf("unicode") != -1) 193 encoding = Encoding.Unicode; 194 else if (ContentType.IndexOf("gbk") != -1) 195 encoding = Encoding.GetEncoding("GBK"); 196 197 StreamReader stream; 198 GZipStream gz = null; 199 200 if (!string.IsNullOrEmpty(response.Headers["Content-Encoding"]) && response.Headers["Content-Encoding"].ToLower() == "gzip") 201 { 202 gz = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress); 203 stream = new StreamReader(gz, encoding); 204 } 205 else 206 { 207 stream = new StreamReader(response.GetResponseStream(), encoding); 208 } 209 string code = stream.ReadToEnd(); 210 stream.Close(); 211 if (gz != null) 212 gz.Close(); 213 response.Close(); 214 return code; 215 } 216 catch (Exception ce) 217 { 218 throw ce; 219 } 220 } 221 } 222 }
效果如下:
上传成功后图片如下: