说明(2017-10-8 23:03:43):
1. 后面的内容都是一些杂七杂八的,零零碎碎的,之前都直接略过了,不过其实还是挺重要的,这次重新学习要认认真真敲一遍。
2. 明天中午9号要回北京了,今晚跟介绍的妹子聊了一个多小时,哎!
3. 下集预告,给图片加水印!
index.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title></title> 5 </head> 6 <body> 7 <form action="index.ashx" method="post" enctype="multipart/form-data"> 8 <input type="file" name="file" /> 9 <input type="text" name="txt" /> 10 <input type="submit" value="上传" /> 11 </form> 12 </body> 13 </html>
index.ashx
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.IO; 6 7 namespace _02_图片上传 8 { 9 /// <summary> 10 /// index 的摘要说明 11 /// </summary> 12 public class index : IHttpHandler 13 { 14 15 public void ProcessRequest(HttpContext context) 16 { 17 context.Response.ContentType = "text/html"; 18 //接收文件数据 19 HttpPostedFile file = context.Request.Files["file"]; 20 if (file == null) 21 { 22 context.Response.Write("未上传图片!"); 23 } 24 else 25 { 26 27 //string fileName = Path.GetFileName(file.FileName); 28 //加上全局唯一标识,防止图片重名 29 Guid g = Guid.NewGuid(); 30 string fileName = Guid.NewGuid().ToString(); 31 //获取扩展名 32 string fileExt = Path.GetExtension(file.FileName); 33 //相对路径 34 string filePath = "image/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/"; 35 //绝对路径 36 //创建文件夹,以年月日命名 37 string fileRealPath = context.Request.MapPath("image/") + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/"; 38 Directory.CreateDirectory(fileRealPath); 39 //判断文件类型,防止上传病毒 40 if (fileExt == ".jpg") 41 { 42 file.SaveAs(fileRealPath + fileName + fileExt); 43 //这个地方的图片路径需要是相对路径,不然不显示 44 context.Response.Write("<html><head></head><body><h1>哈哈哈哈</h1><img src='" + filePath + fileName + fileExt + "'/></body></html>"); 45 } 46 47 } 48 } 49 50 public bool IsReusable 51 { 52 get 53 { 54 return false; 55 } 56 } 57 } 58 }