前台网页代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" οnclick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
后台上传事件控制代码:
protected void Button1_Click(object sender, EventArgs e)
{
string filename=FileUpload1.FileName;
string size = FileUpload1.PostedFile.ContentLength.ToString();
string[] myfile = filename.Split('.');
string dotname = myfile[myfile.Length - 1].ToString().ToLower();
string type = FileUpload1.PostedFile.ContentType;
string type2 = filename.Substring(filename.LastIndexOf(".") + 1);
string imgpath = Server.MapPath("~/Upimg") + "\\";
string filepath = Server.MapPath("~/Upfile") + "\\";
string folder = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();
if (type2 == "jpg" || type2 == "png")
{
image1.Visible = true;
if (!System.IO.Directory.Exists(imgpath + folder))
{
//自动生成文件夹
System.IO.Directory.CreateDirectory(imgpath + folder);
}
Random myrdn = new Random(); //产生随机数
string newfilename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + myrdn.Next(10000).ToString() + "." + dotname;
FileUpload1.SaveAs(imgpath + folder + "\\" + newfilename);
string wpath = "~\\Upimg\\" + folder + "\\" + newfilename;
image1.ImageUrl = wpath;
Label1.Text = "原始文件名" + filename + "</br>存储文件名:" + newfilename + "</br>文件大小:" + size + "</br>文件类型:" + type2 + "</br>文件后缀" + type + "</br>文件虚拟路径:" + wpath;
}
else
{
if (!System.IO.Directory.Exists(filepath + folder))
{
System.IO.Directory.CreateDirectory(filepath + folder);
}
Random myrdn = new Random();//产生随机数
//日期,时间,随机数和后缀名
string newfilename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + myrdn.Next(10000).ToString() + "." + dotname;
image1.Visible = false;
string wpath = "Upfile\\" + folder + newfilename;
FileUpload1.SaveAs(filepath + folder + "\\" + newfilename);
Label1.Text = "原始文件名" + filename + "<br>存储文件名:" + newfilename + "<br>文件大小" + size + "<br>文件类型" + type2 + "<br>文件后缀" + type + "<br>文件虚拟路径" + wpath;
}
}