C# 上传图片
html代码
<body>
<%--enctype="multipart/form-data" 上传文件--%>
<form runat="server" id="regForm" style="width: 700px;" enctype="multipart/form-data" class="form-horizontal form-inline" method="post" >
<input type="file" id="face" name="face">
</form>
</body>
aspx.cs文件中的代码
string uploadpath ="";//图片文件名字
HttpPostedFile face = Request.Files["face"];//上传图片的源路径
string currentpath = "/userFace/";//上传后的图片路径
string filepath = Server.MapPath(currentpath);//文件夹名用来存放下载来的图片
if (face.ContentLength>0)
{
string file_name = System.DateTime.Now.ToString("yyyyMMddHHmmss");//新文件名
string sPath = System.DateTime.Now.ToString("yyyy-MM-dd");//创建日期文件夹
string file_ext = System.IO.Path.GetFileName(face.FileName).Split('.')[1];//截取文件后缀
string ext = face.ContentType;//获取文件类型
if (ext == "image/jpeg" || ext == "image/gif" || ext == "image/png")
{
string spath2 = filepath + sPath;
if (!Directory.Exists(spath2))//判断日期文件夹是否存在
{
Directory.CreateDirectory(spath2);//创建日期文件夹
}
string fpath=filepath+ sPath+"\\" + file_name + "." + file_ext;//上传图片的完整路径
uploadpath = currentpath + sPath + "/" + file_name + "." + file_ext;//数据库存放的上传图片的路径
face.SaveAs(fpath);//创建图片
}
}