上传文件的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 }
上传文件的C#代码的更多相关文章
- C# FTP上传文件至服务器代码
C# FTP上传文件至服务器代码 /// <summary> /// 上传文件 /// </summary> /// <param name="fileinfo ...
- Java上传文件FTP服务器代码
1. 在实际的应用重,通常是通过程序来进行文件的上传. 2. 实现java上传文件到ftp服务器中 新建maven项目 添加依赖 <dependency> <groupId>c ...
- FastDFS的配置、部署与API使用解读(2)以字节方式上传文件的客户端代码(转)
本文来自 诗商·柳惊鸿 Poechant CSDN博客,转载请注明源地址:FastDFS的配置.部署与API使用解读(2)上传文件到FastDFS分布式文件系统的客户端代码 在阅读本文之前,请您先通过 ...
- vue.js异步上传文件前后端代码
上传文件前端代码如下: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type&q ...
- nginx 服务器在上传文件出现413代码的解决方法
打开nginx主配置文件nginx.conf 找到http{}段,添加client_max_body_size 20m;
- FastDFS的配置、部署与API使用解读(3)以流的方式上传文件的客户端代码(转)
调用的API为: String[] upload_file( String group_name,//组名,不指定则可设为null long file_size,//文件大小,必须制定 UploadC ...
- Ajax方式上传文件
用到两个对象 第一个对象:FormData 第二个对象:XMLHttpRequest 目前新版的Firefox 与 Chrome 等支持HTML5的浏览器完美的支持这两个对象,但IE9尚未支持 For ...
- MVC上传文件
ASP.NET MVC上传文件是必段撑握的知识.加强训练才是.以前Insus.NET曾使用第三方MyAjaxForm.js :http://www.cnblogs.com/insus/p/378548 ...
- 图片上传和显示——上传图片——上传文件)==ZJ
http://www.cnblogs.com/yc-755909659/archive/2013/04/17/3026409.html aspx上传 http://www.cnblogs.com/mq ...
随机推荐
- spring-boot 示例大全
spring-boot-demo Spring Boot 学习示例,将持续更新... 本项目基于spring boot 最新版本(2.1.7)实现 什么是spring-boot Spring Boot ...
- 安装yarn实况
[**前情提要**]最近在gayhub上面得到一个开源项目,遂准备研究一下源码,当然第一步就是要把项目运行起来.然后看了一下技术栈,发现包管理工具是使用yarn,以前也听说过yarn但是也没有具体使用 ...
- 前后端分离后台api接口框架探索
前言 很久没写文章了,今天有时间,把自己一直以来想说的,写出来,算是一种总结吧! 这篇文章主要说前后端分离模式下(也包括app开发),自己对后台框架和与前端交互的一些理解和看法. 前后端分离 ...
- 利用hash或history实现单页面路由
目录 html代码 css代码 JavaScript代码 hash方式 history 方式 浏览器端代码 服务器端 在chrome(版本 70.0.3538.110)测试正常 编写涉及:css, h ...
- 使用JMS接口接入WebSphere MQ消息
在你的应用程序中利用IBM WebSphere MQ消息中间件提供Java消息服务开放接口. IBM WebSphere MQ(WMQ)是一套面向消息的中间件(message-oriented mid ...
- 面试java后端面经_4
作者:早该变坏链接:https://www.nowcoder.com/discuss/157627来源:牛客网 情话部分: 当有自己心仪的小姐姐,又没确定关系,有时候分享彼此爱情观的时候,你就可以开始 ...
- ggplot2: how to check the color and coreponding value pairs
The way to check the color and coreponding value pairs in ggplot2 To see what colors are used to mak ...
- maven学习(2)仓库和配置
1:本地资源库.中央存储库.远程存储库 1.1 本地资源库 当你建立一个 Maven 的项目,Maven 会检查你的 pom.xml 文件,以确定哪些依赖需要下载.首先,Maven 将从本地资源库 ...
- SpringMVC源码剖析5:消息转换器HttpMessageConverter与@ResponseBody注解
转自 SpringMVC关于json.xml自动转换的原理研究[附带源码分析] 本系列文章首发于我的个人博客:https://h2pl.github.io/ 欢迎阅览我的CSDN专栏:Spring源码 ...
- 【在 Nervos CKB 上做开发】Nervos CKB脚本编程简介[2]:脚本基础
CKB脚本编程简介[2]:脚本基础 原文作者:Xuejie 原文链接:Introduction to CKB Script Programming 2: Script 本文译者:Shooter,Jas ...