2011-03-25 122 views
1

我有一個asp.net網頁表單網站,我期待創建一個控件,允許用戶瀏覽圖像,然後將圖像保存到數據庫中。我知道將圖像保存到數據庫是不好的做法,但那就是我被告知要做的事!asp.net上傳圖像

有沒有人有任何建議最好的方法來做到這一點?

感謝

回答

4

來自樣本:

var intDoccumentLength = FileUpload1.PostedFile.ContentLength; 
var newDocument = new byte[intDoccumentLength]; 

var stream = FileUpload1.PostedFile.InputStream; 
stream.Read(newDocument, 0, intDoccumentLength); 
var sqlConnection = new SqlConnection(sqlConnectionString); 
sqlConnection.Open(); 

var sqlQuery = "INSERT INTO dbo.DocumentData (DocName, DocBytes, DocData, DocCreatedAt) VALUES (@DocName, @DocBytes, @DocData, @DocCreatedAt);" 
          + "SELECT CAST(SCOPE_IDENTITY() AS INT)"; 

sqlCommand = new SqlCommand(sqlQuery, sqlConnection); 
sqlCommand.Parameters.Add("@DocName", SqlDbType.NVarChar, 255); 
sqlCommand.Parameters.Add("@DocBytes", SqlDbType.Int); 
sqlCommand.Parameters.Add("@DocData", SqlDbType.VarBinary); 
sqlCommand.Parameters.Add("@DocCreatedAt", SqlDbType.DateTime); 

sqlCommand.Parameters["@DocName"].Value = FileUpload1.PostedFile.FileName; 
sqlCommand.Parameters["@DocBytes"].Value = intDoccumentLength; 
sqlCommand.Parameters["@DocData"].Value = newDocument; 
sqlCommand.Parameters["@DocCreatedAt"].Value = DateTime.Now; 

var newDocumentId = (Int32) sqlCommand.ExecuteScalar(); 
sqlConnection.Close(); 
6

基本上所有你需要的是一個FileUpload控制和一些代碼,將其保存到數據庫中。 (而且你自然也想做一些輸入檢查。)有一個很老的教程,它很好地解釋了這個概念hereThis one稍微近一點。但有no shortage of others

0

工具箱中有fileupload工具可用。你只需要在令狀按鈕的單擊事件下面的代碼..

string filename = FileUpload1.FileName.ToString(); 
     if (filename != "") 
      { 

       ImageName = FileUpload1.FileName.ToString(); 

       ImagePath = Server.MapPath("Images"); 
       SaveLocation = ImagePath + "\\" + ImageName; 
       SaveLocation1 = "~/Image/" + ImageName; 
       sl1 = "Images/" + ImageName; 
       FileUpload1.PostedFile.SaveAs(SaveLocation); 
      } 

,我希望你在你的數據庫中的圖像列這樣的話只需要插入你的插入查詢字符串SL1 ..

+1

並且不要忘記在執行該查詢後從服務器刪除文件。否則會變得混亂。 ;-) – Koen 2011-03-25 12:18:17