简单介绍
这个由Htmlpage1.html嵌套htmlPage2.html
主要是为了 上传时不会跳转到FileUpload.ashx
这实例来自http://www.luofenming.com 如不懂可以问我 我可以免费教你
以下是Htmlpage1.html代码
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <meta charset="utf-8" /> </head> <body> 上传主图片 : <input id="imagepath" type="text" name="imagepath" /><br /> <iframe src="HtmlPage2.html" name="upload" align="top" frameborder="0" style="height: 53px; width: 400px;"></iframe> </body> </html>
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <meta charset="utf-8" /> </head> <body> <form method="post" target="upload" action="FileUpload.ashx" enctype="multipart/form-data"> <input type="file" name="fileUp" /> <input type="submit" value="上传图片" /> </form> </body> </html>
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace Share.AdminWeb.Article { /// <summary> /// FileUpload 的摘要说明 /// </summary> public class FileUpload : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; HttpPostedFile file = context.Request.Files[0];//获取上传的文件 if (file != null) { string fileName = Path.GetFileName(file.FileName);//获取文件名GetFileName方法只返回文件名与扩展名 string fileExt = Path.GetExtension(fileName);//获取扩展名 string fileToLower = fileExt.ToLower(); if (fileToLower != "" && (fileToLower == ".jpg"|| fileToLower==".png"|| fileToLower== ".gif")) { string newfileName = Guid.NewGuid().ToString();//得到一个随机名 string dir = "/images/" + DateTime.Now.ToString("yyyyMMdd") + "/"; if (!Directory.Exists(context.Request.MapPath(dir)))//如果没有文件指定的目录就创建 { Directory.CreateDirectory(context.Request.MapPath(dir)); } string fullDir = dir + newfileName + fileExt;//构建完整的途径包括文件名和扩展名 file.SaveAs(context.Request.MapPath(fullDir));//保存文件到完整途径 context.Response.Write("OK<script>window.parent.document.getElementById(\"imagepath\").value = \"" + fullDir + "\";window.setTimeout(function () {location.href = 'upload.aspx';}, 2000);</script>"); } else { context.Response.Write("请选择要上传的图片,格式为jpg,png,gif<script>window.setTimeout(function () {location.href = 'upload.aspx';}, 2000);</script>"); } } else { } //context.Response.Write("Hello World"); } public bool IsReusable { get { return false; } } } }