c# - 如何使用 C# 和 ASP.NET MVC 插入从表单中获取的图像并将其作为字节存储到数据库中

标签 c# asp.net-mvc

我想将一些包括图像(以字节为单位)的数据插入到数据库中。我该怎么做?

Stream fs = img.ImageFile.PostedFile.InputStream;

BinaryReader br = new BinaryReader(fs);

byte[] bytes = br.ReadBytes((Int32)fs.Length);

以上是我试过的

最佳答案

获取文件字节

byte[] file = new byte[img.ImageFile.PostedFile.ContentLength];

您的查询(作为模板)

insert into table file values @file
new SqlParameter("@file",file)

新代码

[HttpPost]
public ActionResult addimage(HttpPostedFileBase ImageFile) 
{ 
  byte[] file = new byte[ImageFile.ContentLength];
  using (SqlConnection con = new SqlConnection(connectionString)) 
  { 
    using (SqlCommand cmd = new SqlCommand("dbo.addimage", con)) 
    { 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.Parameters.AddWithValue("@tname", file);
      con.Open(); 
      status = cmd.ExecuteNonQuery(); 
    } 
  }
}

关于c# - 如何使用 C# 和 ASP.NET MVC 插入从表单中获取的图像并将其作为字节存储到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56093618/

相关文章:

c# - 将两个字符串添加到二维列表

JavaScript 文件以日语(或其他亚洲语言)显示

asp.net-mvc - 是否仍支持 MetaWeblog API?

asp.net-mvc - 不能使用以 "name"结尾的数据属性?

asp.net-mvc 我在哪里放我自己的代码

c# - 为什么 ViewBag.SomeProperty 在属性不存在时不抛出异常?

c# - 是否可以创建自定义 ASP.NET MVC 强类型 HTML Helper?

c# - 从文件路径中删除 'head' 目录

c# - 不从循环返回值

c# - 为什么 finally 没有被执行?