[轉貼]如何上傳圖檔到 Server 端的資料庫

包含 c#, asp.net, vb.net, delphi.net 等 .net framework 的開發討論區
回覆文章
頭像
tim
文章: 1384
註冊時間: 2008年 11月 26日, 00:49

[轉貼]如何上傳圖檔到 Server 端的資料庫

文章 tim »

轉貼自,
http://delphi.ktop.com.tw/topic.asp?TOPIC_ID=58085

代碼: 選擇全部

     
    using System.Web; 
    using System.IO; 
     
      foreach ( HttpPostedFile aFile in Request.Files ) 
      { 
        if ( aFile.ContentLength > 0 ) 
        { 
          string[] aSplit = aFile.FileName.Split( '\' ); 
          string aFullPath = Server.MapPath( @"TempDir" + aSplit[aSplit.Length-1] ); 
          aFile.SaveAs( aFullPath ); 
     
          DBCommand1.CommandText =  
            " insert into TABLE                 " + 
            "           ( FileName,             " + 
            "             FileContent )         " + 
            "    values ( @F1,                  " +  
            "             @F2         )         "; 
          DBCommand1.Parameters.Add( "@F1", SqlDbType.VarChar ); 
          DBCommand1.Parameters.Add( "@F2", SqlDbType.Image ); 
          DBCommand1.Parameters["@F1"].value = aFullPath; 
     
          FileStream aStream = new FileStream(  aFullPath, FileMode.OpenOrCreate, FileAccess.Read );           
          using ( BinaryReader aReader = new BinaryReader( aStream ) ) 
          { 
            DBCommand1.Parameters["@F2"].value = aReader.ReadBytes( (int)aReader.BaseStream.Length ); 
            aReader.Close(); 
          } 
     
          DBCommand1.Connection.Open(); 
          try 
          { 
            DBCommand1.ExecuteNonQuery(); 
          } 
          catch ( Exception Ex ) 
          { 
            lbMessage.value +=  
              string.format( "上傳檔案失敗, 檔案名稱: {0}  原因:{1}",  
              aFile.FileName, Ex.Message ); 
          } 
          finally 
          { 
            DBCommand1.Connection.Close(); 
          } 
     
          File.Delete( aFullPath ); 
     
        } 
      } 
 
多多留言, 整理文章, 把經驗累積下來.....
回覆文章