aspx文件中的代码如下:
<form id="form1" runat="server">
<div>
<asp:FileUpload id="File1" type="file" runat="server" />
<asp:Button id="Button1" type="button" value="button" runat="server"
onclick="Button1_Click1" Text="上传图片" />
<div><asp:Label id="Label1" runat="server" />
</div>
</div>
</form>(鼠标移到代码上去,在代码的顶部会出现四个图标,第一个是查看源代码,第二个是复制代码,第三个是打印代码,第四个是帮助)功能:C#图片(文件)上传功能
作者:wangsdong
来源:www.aspbc.com
原创文章,转载请保留此信息,谢谢
aspx.cs文件中的代码
protected void Button1_Click1(object sender, EventArgs e)
{
string currentpath = "/upfiles/"; //这是上传后的图片路径
string filepath = Server.MapPath(currentpath); //文件夹名,以日期为文件夹名,图片所在这个地方
HttpPostedFile userPostedFile = Request.Files["File1"];
if (userPostedFile.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(userPostedFile.FileName).Split('.')[1];
string ext = userPostedFile.ContentType; //获取文件类型
if (ext == "image/pjpeg" || ext == "image/gif"||ext=="image/x-png")
{
string sPath2 = filepath + sPath;
if (!Directory.Exists(sPath2)) //判断日期文件夹是否存在
{
Directory.CreateDirectory(sPath2);//创建日期文件夹
}
string fpath = filepath + sPath + "\\" + file_name + "." + file_ext;
string uploadpath = currentpath + sPath + "/" + file_name + "." + file_ext;
userPostedFile.SaveAs(fpath);
Label1.Text = uploadpath;
}
else
{
Label1.Text = "文件格式不正确";
}
}
}(鼠标移到代码上去,在代码的顶部会出现四个图标,第一个是查看源代码,第二个是复制代码,第三个是打印代码,第四个是帮助)注意当前目录下必须有upfiles文件夹,最后上传的文件放到upfiles文件夹下面以当天日期为文件夹的文件夹里面。
这样就行了,这个里面还介绍创建文件夹功能,其他地方也是用的着的。
