If we now realize the function to upload a file, then how to do it?
First, build a html file upload page
<!--enctype="multipart/form-data"加上此编码,只有这样用户选择的文件数据(文件流)才会放在请求报文中,发送给服务器-->
<form action="ProcessFileUp.ashx" method="post" enctype="multipart/form-data">
<input type="file" name="fileUp">
<input type="submit" value="上传">
</form>
Renderings:
Click upload, enter the second step
General handler Second, build a file upload
using System;
using System.Web;
using System.IO;
using System.Collections;
namespace WepApp.文件上传
{
/// <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);
//调用IsPicture方法判断是否为图片扩展名
if (IsPicture(fileExt))
{
//1.对上传文件进行重命名
string newfileName = Guid.NewGuid().ToString();
//2.将上传的文件放在不同的目录下面,根据日期
string dir = "/ImageUpload/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
//3.判断是否含有该目录
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("<html><body><img src='"+ fullDir + "'></body></html>");
}
else
{
context.Response.Write("只能上传图片文件");
}
}
else
{
context.Response.Write("请选择上传文件");
}
}
//判断是否是图片的格式
public bool IsPicture(string fileext)
{
ArrayList a1 = new ArrayList();
a1.Add(".bmp");
a1.Add(".jpg");
a1.Add(".png");
a1.Add(".tif");
a1.Add(".gif");
a1.Add(".pcx");
if (a1.Contains(fileext))
{
return true;
}
return false;
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Third, the summary
Code section to complete a user to upload files to the web server functionality is implemented, focusing on the following code