2009-01-26 38 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(); 

让我知道,如果你想存储程序代码也是如此。

相关问题