一、解决方案目录结构
二、FileUp.html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<!--enctype="multipart/form-data":如果要上传文件必须加上该属性,指定相应的编码。
只有这样用户选择的文件数据(文件流)才会放在请求报文中,发送给服务器。
表单中的其它表单元素(文本框等),也会发送到服务端,但是格式也变了,
但是在服务端还是按照以前的方式进行接收-->
<!--如果表单不需要上传文件就不用加enctype--->
<form method="post" action="FileUp.ashx" enctype="multipart/form-data">
<input type="file" name="fileUp" />
<input type="text" name="txtName" />
<input type="submit" value="上传" />
</form>
</body>
</html>三、FileUp.ashx后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace UploadFileWebApp
{
/// <summary>
/// FileUp 的摘要说明
/// </summary>
public class FileUp : 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 == ".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;
}
}
}
}

782

被折叠的 条评论
为什么被折叠?



