2009-01-26 37 views
3

我知道有一種方法可以將圖像作爲圖像類型或varbinary類型上傳到數據庫,但是,我搜索了整個星期,我無法找到任何可以幫助我的東西,所以這真是我的最後一招,如果任何人都知道如何將圖像上傳到數據庫,我正在使用SQL Server 2005 Express。使用ASP.Net MVC將圖像上傳到SQL Server 2005?

感謝

回答

0

如果你沒事存儲圖像爲VARCHAR,這裏是一些代碼來這樣做。

String b64; 
    using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) 
    { 
     this.pic.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
     Byte[] bytes = ms.ToArray(); 
     b64 = Convert.ToBase64String(bytes); 
    } 
    using (SqlConnection conn = new SqlConnection(ConnectionString)) 
    { 
     using (SqlCommand cmd = new SqlCommand("UPDATE [settings] SET [value] = @val WHERE [id] = 2", conn)) 
     { 
      conn.Open(); 
      cmd.Parameters.Add(new SqlParameter("@val", b64)); 
      cmd.ExecuteNonQuery(); 
      conn.Close(); 
     } 
    } 
2

您應該能夠訪問請求的文件集合並獲取每個上傳文件的HttpPostedFile實例。從文件中獲取InputStream並將其讀入字段數組中的列屬性。我假設這是你的DAL如何將varbinary映射到你的業務類 - 如果沒有,說它是一個本地圖像,那麼你需要在保存之前進行轉換。下面的例子使用LINQ2SQL。

MyClass obj = new MyClass(); 
obj.Name = Request["name"]; // other properties 
obj.Alt = Request["altText"]; 

HttpPostedFile file = Request.Files[0]; 
if (file != null) 
{ 
    obj.Image image = new byte[file.ContentLength]; 
    file.Read(obj.Image,0,file.ContentLength]; 
} 

using (DataContext context = new DataContext()) 
{ 
    context.InsertOnSubmit(obj); 
    context.SubmitChanges(); 
} 
0

假設你有一個名爲TestProc存儲過程,它需要一個類型爲IMAGE的@data一個參數,C#代碼可能如下:

SqlConnection conn = new SqlConnection("<your connection string>"); 
conn.Open(); 

SqlCommand cmd = new SqlCommand("TestProc", conn); 
cmd.CommandType = CommandType.StoredProcedure; 

SqlParameter param = new SqlParameter("@data", SqlDbType.Image); 
param.Value = System.IO.File.ReadAllBytes("any_file.jpg"); 
cmd.Parameters.Add(param); 

cmd.ExecuteNonQuery(); 

讓我知道,如果你想存儲程序代碼也是如此。

相關問題