[轉貼]如何上傳圖檔到 Server 端的資料庫
發表於 : 2008年 11月 26日, 03:12
轉貼自,
http://delphi.ktop.com.tw/topic.asp?TOPIC_ID=58085
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 );
}
}