html页面:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<!--enctype="multipart/form-data":如果要上传文件必须加上该属性,指定相应的编码。只有这样用户选择的文件数据(文件流)才会放在请求报文中,发送给服务器。表单中的其它表单元素(文本框等),也会发送到服务端,但是格式也变了,但是在服务端还是按照以前的方式进行接收-->
<!--如果表单不需要上传文件就不用加enctype--->
<form method="post" action="ProcessFileUp.ashx" enctype="multipart/form-data">
<input type="file" name="fileUp"/>
<input type="text" name="txtName" />
<input type="submit" value="上传" />
</form>
</body>
</html>
服务器端接收数据(ProcessFileUp.ashx.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace Project.WebApp._2015_5_27
{
/// <summary>
/// ProcessFileUp 的摘要说明
/// </summary>
public class ProcessFileUp : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
HttpPostedFile file=context.Request.Files[0];//获取上传的文件.
if (file.ContentLength>0)
{
//对上传的文件类型进行校验。
string fileName =Path.GetFileName(file.FileName);//从全路径文件名(绝对路径)中获取上传文件的名称及扩展名。
string fileExt = Path.GetExtension(fileName);//获取用户上传的文件扩展名。
if (fileExt == ".jpg" || fileExt == ".png")
{
//1.对上传文件进行重命名
string newfileName = Guid.NewGuid().ToString(); //全球唯一的文件名
//2:将上传的文件放在不同的目录下面
string dir = "/ImageUpload/"+DateTime.Now.Year+"/"+DateTime.Now.Month+"/"+DateTime.Now.Day+"/";
//创建文件夹
if (!Directory.Exists(context.Request.MapPath(dir)))
{
Directory.CreateDirectory(context.Request.MapPath(dir));
}
string fullDir = dir + newfileName + fileExt; //文件存放的完整路径。
file.SaveAs(context.Request.MapPath(fullDir));
// file.SaveAs(context.Request.MapPath("/ImageUpload/"+fileName));//完成文件的保存。这种方式 文件名容易冲突。
context.Response.Write("<html><body><img src='"+fullDir+"'/></body></html>");
}
else
{
context.Response.Write("只能上传图片文件");
}
}
else
{
context.Response.Write("请选择上传文件");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}