上传文件的C#代码

  1 <%@ WebHandler Language="C#" Class="UpLoadFile" %>
  2 
  3 using System;
  4 using System.Collections;
  5 using System.Collections.Generic;
  6 using System.Drawing;
  7 using System.Drawing.Drawing2D;
  8 using System.Threading;
  9 using System.Web;
 10 using System.Web.Mvc;
 11 using System.Web.Script.Serialization;
 12 using System.IO;
 13 
 14 /// <summary>
 15 /// UpLoadHandler 的摘要说明
 16 /// </summary>
 17 public class UpLoadFile : IHttpHandler
 18 {
 19     //文件上传目录
 20     private string uploadFolder = "/UserImages/";
 21     //定义允许上传的文件扩展名
 22     private String fileTypes = "jpg,gif,jpeg,png,doc,pdf,html,htm";
 23     //最大文件大小 1MB=1000000byte
 24     private int maxSize = 20000000;
 25 
 26     public void ProcessRequest(HttpContext context)
 27     {
 28         UpLoadData data = new UpLoadData();
 29         //context.Response.ContentType = "text/plain";
 30 
 31         HttpFileCollection files = context.Request.Files;
 32         try
 33         {
 34             if (files.Count <= 0 || files[0] == null)
 35             {
 36                 ReturnError(context, "请选择文件。");
 37             }
 38 
 39             HttpPostedFile file = files[0];
 40 
 41             if (file.InputStream == null || file.InputStream.Length > maxSize)
 42             {
 43                 ReturnError(context, "上传文件大小超过限制。");
 44             }
 45 
 46             string fileExt = System.IO.Path.GetExtension(file.FileName).ToLower();
 47             ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));
 48             if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
 49             {
 50                 ReturnError(context, "上传文件扩展名是不允许的扩展名。");
 51             }
 52 
 53             //添加新文件
 54             string fileName = GetDateTimeNO().ToString();
 55             string folderName = context.Request.QueryString["folderName"];
 56             string dateName = DateTime.Now.ToString("yyyy-MM-dd");
 57             String dirPath = context.Server.MapPath("\UserImages\" + folderName + "\" + dateName + "\");
 58             if (!Directory.Exists(dirPath))
 59             {
 60                 Directory.CreateDirectory(dirPath);
 61             }
 62             string path = context.Server.MapPath(uploadFolder) + folderName + "\" + dateName + "\";
 63             string fileFullName = fileName + fileExt;
 64             string savePath = path + fileFullName;
 65             file.SaveAs(savePath);
 66 
 67             Image image = Image.FromFile(savePath);
 68 
 69 
 70 
 71             switch (folderName)
 72             {
 73                 case "Reports":
 74                     Image img = Thumbnail(image, 188, 140);
 75 
 76                     img.Save(path + "/S_" + fileFullName);
 77 
 78                     image.Dispose();
 79                     break;
 80                 case "Activity":
 81                     Image img2 = Thumbnail(image, 360, 270);
 82 
 83                     img2.Save(path + "/S_" + fileFullName);
 84 
 85                     image.Dispose();
 86                     break;
 87 
 88                 case "ActivityBrend":
 89                     Image img3 = Thumbnail(image, 280, 266);
 90 
 91                     img3.Save(path + "/S_" + fileFullName);
 92 
 93                     image.Dispose();
 94                     break;
 95 
 96                 case "ReleaseCars":
 97                     Image img4 = Thumbnail(image, 280, 266);
 98 
 99                     img4.Save(path + "/S_" + fileFullName);
100 
101                     image.Dispose();
102                     break;
103 
104             }
105             data.FileName = dateName + "/" + fileName + fileExt;
106             data.FileUrl = uploadFolder + folderName + "/" + dateName + "/" + fileName + fileExt;
107         }
108         catch (Exception e)
109         {
110             data.Error = e.Message;
111         }
112         context.Response.Write(new JavaScriptSerializer().Serialize(data));
113         context.Response.End();
114     }
115 
116     private void DeleteFile(HttpContext context, string fileName)
117     {
118         String delFilePath = context.Server.MapPath(fileName);
119         if (File.Exists(delFilePath))
120         {
121             new FileInfo(delFilePath).Delete();
122         }
123     }
124 
125     private void ReturnError(HttpContext context, string error)
126     {
127         UpLoadData data = new UpLoadData();
128         data.Error = error;
129         context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
130         context.Response.Write(new JavaScriptSerializer().Serialize(data));
131         context.Response.End();
132     }
133 
134     #region 按日期时间生成编号
135     /// <summary>
136     /// 按日期生成编号
137     /// </summary>
138     /// <param name="num">位数(默认18位)</param>
139     /// <returns>编号</returns>
140     public long GetDateTimeNO(int num = 18)
141     {
142         if (num > 20) num = 20;
143         string formatbase = "yyyyMMddhhmmssffffff";
144         Thread.Sleep(1);
145         return long.Parse((DateTime.Now.ToString(formatbase)).Substring(0, num));
146     }
147     /// <summary>
148     /// 按日期生成编号(后4位根据种子)
149     /// </summary>
150     /// <param name="rand">种子</param>
151     /// <param name="num">位数(默认18位)</param>
152     /// <returns>编号</returns>
153     public long GetDateTimeNO(int seed, int num = 18)
154     {
155         long result = 0;
156         if (num > 20) num = 20;
157         string formatbase = "yyyyMMddhhmmssffffff";
158         string seedstr = seed.ToString().PadLeft(4, '0');
159         result = long.Parse((DateTime.Now.ToString(formatbase)).Substring(0, num - 4) + seedstr);
160         return result;
161     }
162     #endregion
163 
164 
165 
166 
167     //缩小图片
168     public Image Thumbnail(Image image, int width, int height)
169     {
170         var newWidth = width;
171         var newHeight = image.Height * newWidth / image.Width;
172 
173         if (newHeight < height)
174         {
175             // Resize with height instead
176             newWidth = image.Width * height / image.Height;
177             newHeight = height;
178         }
179 
180         var tempImage = new Bitmap(newWidth, newHeight);
181 
182         using (var graphic = Graphics.FromImage(tempImage))
183         {
184             //指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
185             graphic.InterpolationMode = InterpolationMode.High;
186 
187             //指定高速度呈现
188             graphic.SmoothingMode = SmoothingMode.HighQuality;
189 
190             //  graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
191 
192             //线性质量设置
193             graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
194             graphic.DrawImage(image, 0, 0, newWidth, newHeight);
195         }
196 
197         var x = (newWidth - width) / 2;
198         var y = 0;
199         var thumbnail = tempImage.Clone(new Rectangle(x, y, width, height), tempImage.PixelFormat);
200 
201         return thumbnail;
202     }
203 
204     public bool IsReusable
205     {
206         get
207         {
208             return false;
209         }
210     }
211 }
212 
213 public class UpLoadData
214 {
215     /// <summary>
216     /// 错误信息
217     /// </summary>
218     public string Error { set; get; }
219     /// <summary>
220     /// 文件名称
221     /// </summary>
222     public string FileName { set; get; }
223     /// <summary>
224     /// 文件路径
225     /// </summary>
226     public string FileUrl { set; get; }
227 
228     public UpLoadData()
229     {
230         this.Error = string.Empty;
231         this.FileName = string.Empty;
232         this.FileUrl = string.Empty;
233     }
234 }
原文地址:https://www.cnblogs.com/xiao-sheng/p/4440067.html