文件上传

在显示页面使用表单POST传送数据

		<form action="TestUpload.ashx"  method="post" enctype="multipart/form-data">
		<input type="file" name="fUplod" /><input type="submit" value="上传" />
		<span id="msgUpload"></span>
		</form>

 在一般处理程序中设置文件传送

View Code
 1  public void ProcessRequest(HttpContext context)
 2                 {
 3                     context.Response.ContentType = "text/plain";
 4                     //可上传的文件类型
 5                     string[] strExt = { "image/jpeg", "image/pjpeg", "jpeg", "jif" };
 6                     List<string> listExt = new List<string>(strExt);
 7                     //可上传的最大大小
 8                     int maxFile = 1024 * 200;  //200Kb
 9                     //获取上传的文件
10                     HttpFileCollection files = context.Request.Files;
11 
12                     if (files.Count > 0)
13                     {
14                         //源文件路径
15                         string Sfile = files[0].FileName;
16 
17                         if (!string.IsNullOrEmpty(Sfile))
18                         {
19                             //文件扩展名
20                             string ext = Path.GetExtension(Sfile);
21                             if (listExt.Contains(files[0].ContentType))
22                             {
23                                 if (files[0].ContentLength < maxFile)
24                                 {
25                                     //随机获取文件名
26                                     Random ra = new Random();
27                                     string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ra.Next(1000, 10000) + ext;
28                                     //上传
29                                     string strPath = context.Request.MapPath("Upload/" + fileName);
30                                     files[0].SaveAs(strPath);
31                                     context.Response.Write("文件上传成功!");
32                                 }
33                                 else
34                                 {
35                                     context.Response.Write("文件大小超过要求!");
36                                 }
37                             }
38                             else
39                             {
40                                 context.Response.Write("不允许上传该类型的文件!");
41                             }
42                         }
43                     }
44                     else
45                     {
46                         context.Response.Write("没有上传文件");
47                     }
48                 }

在web.config中设置文件传送的最大限制

 <system.web>
      <!--单位是Kb-->
      <httpRuntime maxRequestLength="200"/>
原文地址:https://www.cnblogs.com/dedeyi/p/2642973.html