AvatarService上传图片(兼容)

Handler

  1     public void ProcessRequest(HttpContext context)
  2     {
  3         context.Response.ContentType = "text/plain";
  4         string action = context.Request["myaction"];
  5         if (action == "upload")
  6         {
  7             string msg = ""; string result = "0"; string ww = "0"; string hh = "0"; string size = "1";//缩放
  8             HttpPostedFile file = context.Request.Files[0];
  9             string ext = Path.GetExtension(file.FileName).ToLower();
 10             if (ext != ".jpg" && ext != ".gif" && ext != ".png" && ext != ".jpeg")
 11             {
 12                 msg = "请您上传jpg、gif、png图片";
 13             }
 14             if (file.ContentLength > 5 * 1024 * 1024)
 15             {
 16                 msg = "请您上传512字节内的图片";
 17             }
 18             string newName = Guid.NewGuid().ToString() + "_" + context.Request["newName"];
 19             string tempPath = "CertPhoto/regpg/";
 20             string img = tempPath + newName + ext;
 21             string filePath = context.Server.MapPath(img);
 22             tempPath = context.Server.MapPath(tempPath);
 23             if (!Directory.Exists(tempPath))
 24             {
 25                 Directory.CreateDirectory(tempPath);
 26             }
 27             using (System.Drawing.Image originalImage = System.Drawing.Image.FromStream(file.InputStream))
 28             {
 29                 int w = originalImage.Width;
 30                 int h = originalImage.Height;
 31                 if (w > 1400 || h > 1400)
 32                 {
 33                     msg = "请您上传大小在1400*1400以内的图片";
 34                 }
 35                 else if (w < 50 || h < 50)
 36                 {
 37                     msg = "请您上传大于50*50的图片";
 38                 }
 39                 else
 40                 {
 41                     if (w > 320 || h > 220)
 42                     {
 43                         float sizeM;
 44                         using (System.Drawing.Image thumb = GetThumbImage(originalImage, 320, 220, true, out sizeM))
 45                         {
 46                             thumb.Save(filePath + ".view.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
 47                             ww = thumb.Width.ToString();
 48                             hh = thumb.Height.ToString();
 49                             size = sizeM.ToString();
 50                         }
 51                     }
 52                     else
 53                     {
 54                         size = "1";
 55                         ww = w.ToString();
 56                         hh = h.ToString();
 57                     }
 58                     file.SaveAs(filePath);//保存原图
 59                     result = "1";
 60                     msg = img;
 61                 }
 62             }
 63             string strWrite = "{ \"result\":" + result + ",\"fileName\":\"" + newName + "\",\"size\":" + size + ",\"msg\":\"" + msg + "\",\"w\":" + ww + ",\"h\":" + hh + "}";
 64             context.Response.Write(strWrite);
 65         }
 66         else if (action == "view")
 67         {
 68             context.Response.ContentType = "image/JPEG";
 69             //清除该页输出缓存,设置该页无缓存 
 70             context.Response.Buffer = true;
 71             context.Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
 72             context.Response.Expires = 0;
 73             context.Response.CacheControl = "no-cache";
 74             context.Response.AppendHeader("Pragma", "No-Cache");
 75 
 76             using (Image viewimg = GetViewImage())
 77             {
 78                 using (MemoryStream ms = new MemoryStream())
 79                 {
 80                     viewimg.Save(ms, ImageFormat.Jpeg);
 81                     context.Response.ClearContent();
 82                     context.Response.BinaryWrite(ms.ToArray());
 83                 }
 84             }
 85         }
 86         else if (action == "save")
 87         {
 88             context.Response.ContentType = "text/plain";
 89             using (Image viewimg = GetViewImage())
 90             {
 91                 try
 92                 {
 93                     //这里没有生成缩略图,如果需要,可以在这里加
 94                     string file = HttpContext.Current.Server.MapPath(context.Request["file"]);
 95                     DeleteImage();
 96                     viewimg.Save(file, ImageFormat.Jpeg);
 97                     context.Response.Write("1");
 98                 }
 99                 catch
100                 {
101                     context.Response.Write("0");
102                 }
103             }
104         }
105         else if (action == "delete")
106         {
107             DeleteImage();
108         }
109     }
110 
111     public static void DeleteImage()
112     {
113         string file = HttpContext.Current.Server.MapPath(HttpContext.Current.Request["file"]);
114         try
115         {
116             if (File.Exists(file))
117             {
118                 File.Delete(file);
119             }
120             if (HttpContext.Current.Request["size"] != "1")
121             {
122                 File.Delete(file + ".view.jpg");
123             }
124         }
125         catch { }
126     }
127 
128     private static Image GetViewImage()
129     {
130         float x = float.Parse(HttpContext.Current.Request["x"]);
131         float y = float.Parse(HttpContext.Current.Request["y"]);
132         float w = float.Parse(HttpContext.Current.Request["w"]);
133         float h = float.Parse(HttpContext.Current.Request["h"]) + 1;
134         float size = float.Parse(HttpContext.Current.Request["size"]);
135         if (size != 1.0f)
136         {
137             x = x / size;
138             y = y / size;
139             w = w / size;
140             h = h / size;
141         }
142         using (Image img = CuteImage(HttpContext.Current.Request["file"], x, y, w, h))
143         {
144             float temp;
145             Image viewimg = GetThumbImage(img, 175, 175, false, out temp);
146             return viewimg;
147         }
148     }
149 
150     private static Image CuteImage(string file, float x, float y, float width, float height)
151     {
152         string oldFile = HttpContext.Current.Server.MapPath(file);
153         using (System.Drawing.Image oldImg = System.Drawing.Image.FromFile(oldFile))
154         {
155             System.Drawing.Image cuteImg = CuteImage(oldImg, x, y, width, height);
156             return cuteImg;
157         }
158     }
159 
160     private static System.Drawing.Image CuteImage(System.Drawing.Image oldImage, float x, float y, float width, float height)//切图
161     {
162         width = Math.Min(oldImage.Width - x, width);
163         height = Math.Min(oldImage.Height - y, height);
164         System.Drawing.Image newBitmap = new Bitmap((int)width, (int)height);
165         using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newBitmap))
166         {
167             g.InterpolationMode = InterpolationMode.High;
168             g.SmoothingMode = SmoothingMode.AntiAlias;
169             g.CompositingQuality = CompositingQuality.HighQuality;
170             g.DrawImage(oldImage, new RectangleF(0, 0, width, height), new RectangleF(x, y, width, height), GraphicsUnit.Pixel);
171             g.Save();
172         }
173         return newBitmap;
174     }
175 
176     /// <summary>
177     /// 得到图片缩略图
178     /// </summary>
179     /// <param name="img">图片对象</param>
180     /// <param name="maxWidth">最大宽度</param>
181     /// <param name="maxHeight">最大高度</param>
182     /// <returns></returns>
183     public static System.Drawing.Image GetThumbImage(System.Drawing.Image img, int maxWidth, int maxHeight, bool isBlock, out float size)
184     {
185         int tWidth;
186         int tHeight;
187         size = 1;
188 
189         if (!isBlock)
190         {
191             tWidth = maxWidth;
192             tHeight = maxHeight;
193         }
194         else
195         {
196             if (!(maxHeight > img.Height && maxWidth > img.Width))
197             {
198                 float HeightMultipier = (float)maxHeight / (float)img.Height;
199                 float WidthMultipier = (float)maxWidth / (float)img.Width;
200                 if (HeightMultipier > 1) HeightMultipier = 1;
201                 if (WidthMultipier > 1) WidthMultipier = 1;
202                 float SizeMultiplier = WidthMultipier < HeightMultipier ? WidthMultipier : HeightMultipier;
203                 size = SizeMultiplier;
204                 tWidth = (int)(img.Width * SizeMultiplier);
205                 tHeight = (int)(img.Height * SizeMultiplier);
206             }
207             else
208             {
209                 tWidth = img.Width;
210                 tHeight = img.Height;
211             }
212         }
213         System.Drawing.Image bitmap = new System.Drawing.Bitmap(tWidth, tHeight);
214 
215         //新建一个画板
216         Graphics g = System.Drawing.Graphics.FromImage(bitmap);
217 
218         //设置高质量插值法
219         g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
220 
221         //设置高质量,低速度呈现平滑程度
222         g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
223 
224         //清空画布并以透明背景色填充
225         g.Clear(Color.Transparent);
226 
227         //在指定位置并且按指定大小绘制原图片的指定部分
228         g.DrawImage(img, new Rectangle(0, 0, tWidth, tHeight),
229             new Rectangle(0, 0, img.Width, img.Height),
230             GraphicsUnit.Pixel);
231         return bitmap;
232     }
233 
234 
235     public bool IsReusable
236     {
237         get
238         {
239             return false;
240         }
241     }

HTML

 1 <input type="file" id="avatarFile" name="avatarFile" onchange="_uploadImg();" />
 2 <input type="hidden" id="imgf" value="" />
 3 <a href="javascript:;" onclick="alert($('#imgf').val());">点击我查看名称</a>
 4 <img id="_viewimg" />
 5 <script type="text/javascript">
 6     var __avatar_handlerUrl = "AvatarService.ashx?time=" + Math.random(); var avatarFileName = "";
 7     function _uploadImg() {
 8         $.ajaxFileUpload({
 9             url: __avatar_handlerUrl, secureuri: false, fileElementId: 'avatarFile',
10             data: { myaction: "upload", newName: "IDfront" },
11             success: function (data) {
12                 var obj = $.parseJSON(data);
13                 if (obj.result == 1) {
14                     var file = obj.msg;
15                     avatarFileName = file;
16                     $("#imgf").val(obj.fileName);
17                     if (obj.size != 1) {
18                         file += ".view.jpg";
19                     }
20                     $("#_viewimg").attr("src", file);
21                 }
22                 else {
23                     alert(obj.msg);
24                 }
25             },
26             error: function () {
27                 alert("上传失败,请检查文件是否符合格式要求。");
28             }
29         });
30     }
31 </script>

JS

  1 jQuery.extend({
  2     createUploadIframe: function (id, uri) {
  3         var frameId = 'jUploadFrame' + id;
  4         if (window.ActiveXObject) {
  5             var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
  6             if (typeof uri == 'boolean') {
  7                 io.src = 'javascript:false';
  8             }
  9             else if (typeof uri == 'string') {
 10                 io.src = uri;
 11             }
 12         }
 13         else {
 14             var io = document.createElement('iframe');
 15             io.id = frameId;
 16             io.name = frameId;
 17         }
 18         io.style.position = 'absolute';
 19         io.style.top = '-1000px';
 20         io.style.left = '-1000px';
 21         document.body.appendChild(io);
 22         return io
 23     },
 24     createUploadForm: function (id, fileElementId, data) {
 25         var formId = 'jUploadForm' + id;
 26         var fileId = 'jUploadFile' + id;
 27         var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
 28         var oldElement = $('#' + fileElementId);
 29         var newElement = $(oldElement).clone();
 30         $(oldElement).attr('id', fileId);
 31         $(oldElement).before(newElement);
 32         $(oldElement).appendTo(form);
 33         //增加文本参数的支持   
 34         if (data) {
 35             for (var i in data) {
 36                 $('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
 37             }
 38         }
 39         //set attributes   
 40         $(form).css('position', 'absolute');
 41         $(form).css('top', '-1200px');
 42         $(form).css('left', '-1200px');
 43         $(form).appendTo('body');
 44         return form;
 45     },
 46     ajaxFileUpload: function (s) {
 47         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout           
 48         s = jQuery.extend({}, jQuery.ajaxSettings, s);
 49         var id = new Date().getTime()
 50         var form = jQuery.createUploadForm(id, s.fileElementId, s.data);
 51         var io = jQuery.createUploadIframe(id, s.secureuri);
 52         var frameId = 'jUploadFrame' + id;
 53         var formId = 'jUploadForm' + id;
 54         // Watch for a new set of requests   
 55         if (s.global && !jQuery.active++) {
 56             jQuery.event.trigger("ajaxStart");
 57         }
 58         var requestDone = false;
 59         // Create the request object   
 60         var xml = {}
 61         if (s.global)
 62             jQuery.event.trigger("ajaxSend", [xml, s]);
 63         // Wait for a response to come back   
 64         var uploadCallback = function (isTimeout) {
 65             var io = document.getElementById(frameId);
 66             try {
 67                 if (io.contentWindow) {
 68                     xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
 69                     xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
 70 
 71                 } else if (io.contentDocument) {
 72                     xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
 73                     xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
 74                 }
 75                 try {
 76                     xml.responseText = $(xml.responseText).html();
 77                 }
 78                 catch (e) { ; }
 79                 //xml.responseText= xml.responseText.replace("<PRE>","").replace("</PRE>","").replace("<pre>","").replace("</pre>","");
 80             } catch (e) {
 81                 jQuery.handleError(s, xml, null, e);
 82             }
 83             if (xml || isTimeout == "timeout") {
 84                 requestDone = true;
 85                 var status;
 86                 try {
 87                     status = isTimeout != "timeout" ? "success" : "error";
 88                     // Make sure that the request was successful or notmodified   
 89                     if (status != "error") {
 90                         // process the data (runs the xml through httpData regardless of callback)   
 91                         var data = jQuery.uploadHttpData(xml, s.dataType);
 92                         // If a local callback was specified, fire it and pass it the data   
 93                         if (s.success)
 94                             s.success(data, status);
 95                         // Fire the global callback   
 96                         if (s.global)
 97                             jQuery.event.trigger("ajaxSuccess", [xml, s]);
 98                     } else
 99                         jQuery.handleError(s, xml, status);
100                 } catch (e) {
101                     status = "error";
102                     jQuery.handleError(s, xml, status, e);
103                 }
104 
105                 // The request was completed   
106                 if (s.global)
107                     jQuery.event.trigger("ajaxComplete", [xml, s]);
108 
109                 // Handle the global AJAX counter   
110                 if (s.global && ! --jQuery.active)
111                     jQuery.event.trigger("ajaxStop");
112 
113                 // Process result   
114                 if (s.complete)
115                     s.complete(xml, status);
116 
117                 jQuery(io).unbind()
118 
119                 setTimeout(function () {
120                     try {
121                         $(io).remove();
122                         $(form).remove();
123 
124                     } catch (e) {
125                         jQuery.handleError(s, xml, null, e);
126                     }
127 
128                 }, 100)
129 
130                 xml = null
131 
132             }
133         }
134         // Timeout checker   
135         if (s.timeout > 0) {
136             setTimeout(function () {
137                 // Check to see if the request is still happening   
138                 if (!requestDone) uploadCallback("timeout");
139             }, s.timeout);
140         }
141         try {
142             // var io = $('#' + frameId);   
143             var form = $('#' + formId);
144             $(form).attr('action', s.url);
145             $(form).attr('method', 'POST');
146             $(form).attr('target', frameId);
147             if (form.encoding) {
148                 form.encoding = 'multipart/form-data';
149             }
150             else {
151                 form.enctype = 'multipart/form-data';
152             }
153             $(form).submit();
154 
155         } catch (e) {
156             jQuery.handleError(s, xml, null, e);
157         }
158         if (window.attachEvent) {
159             document.getElementById(frameId).attachEvent('onload', uploadCallback);
160         }
161         else {
162             document.getElementById(frameId).addEventListener('load', uploadCallback, false);
163         }
164         return { abort: function () { } };
165     },
166     uploadHttpData: function (r, type) {
167         var data = type == "xml" ? r.responseXML : r.responseText;
168         // If the type is "script", eval it in global context   
169         if (type == "script")
170             jQuery.globalEval(data);
171         // Get the JavaScript object, if JSON is used.   
172         if (type == "json")
173             eval("data = " + data);
174         // evaluate scripts within html   
175         if (type == "html")
176             jQuery("<div>").html(data).evalScripts();
177         return data;
178     }
179 })

 

posted on 2014-01-24 14:24  slnt  阅读(476)  评论(0编辑  收藏  举报

导航