//前台代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.ASPx.cs" Inherits="test" %>
<!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" CSSClass="input3" Width="290px"/>
<ASP:Button ID="Button1" runat="server" Text="上傳圖片並創建文件夾" OnClick="Button1_Click" />
</div>
</form>
</body>
</Html>
//後台代碼
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string UploadFileName, UploadFileLastName;
UploadFileName = FileUpload1.PostedFile.FileName;//文件在本地的原始位置
UploadFileLastName = UploadFileName.Substring(UploadFileName.LastIndexOf(".") + 1);//得到文件的擴展名
Random rd = new Random();//產生隨機數
int valationNo = 10 + rd.Next(99);//產生隨機數
string suiji = valationNo.ToString();//產生隨機數
string UpLoadFileTime = DateTime.Now.ToString("yyyyMMddHHmmss") + suiji;//得到系統時間並加上隨機數以便生成上傳圖片名稱
string NewUploadFileName = UpLoadFileTime + "." + UploadFileLastName;//產生上傳圖片的名稱
string UserDirectory = "TestFile";//所要創建文件夾的名字,實際運用中可為用戶注冊ID
string UserPath = Server.MapPath("UploadFiles").ToString() + "\\" + UserDirectory + "\\" + "ProductsImages";
if (!Directory.Exists(UserPath)) //如果文件夾不存在則創建
{
Directory.CreateDirectory(UserPath);
}
FileUpload1.PostedFile.SaveAs(NewUploadPahtName);//用保存的方法將圖片上載
string sUser_ProductsImageUrl = "UploadFiles/" + UserDirectory + "/" + "ProductsImages/" + NewUploadFileName;//得到服務端圖片的虛擬路徑
//Response.Write(sUser_ProductsImageUrl);
}
}
http://www.cnblogs.com/zm235/archive/2006/09/23/512673.Html