程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> 關於ASP.NET >> asp.net2.0上傳圖片並為用戶創建相應文件夾

asp.net2.0上傳圖片並為用戶創建相應文件夾

編輯:關於ASP.NET

//前台代碼

<%@ 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"/>&nbsp;&nbsp;&nbsp;&nbsp;
  <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);
  }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved