c# - 将图像添加到数据库

标签 c# asp.net-mvc entity-framework

我试图将两个不同的图像添加到数据库,但它只添加了一个,然后为第二个值添加了相同的图像。

这是我向数据库添加很多照片的 Controller

public ActionResult Create([Bind(Include = "id,title,bodyofarticle")] article article )
{
    if (ModelState.IsValid)
    {
         db.articles.Add(article);
         db.SaveChanges();
        foreach (string file in Request.Files)
        {
            HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;

            string saveFileName = Path.GetFileName(hpf.FileName);
            string location = Path.Combine(Server.MapPath("~/Images/" + hpf.FileName));
            Request.Files[file].SaveAs(location);
            image imag = new image();
            imag.url = Url.Content("~/images/" + saveFileName);
            imag.articleid = article.id;
            db.image.Add(imag);
            article.images.Add(imag);
            db.SaveChanges();

        }
    }   
    return RedirectToAction("Index");
}

这是 View

@using (Html.BeginForm( "Create", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{    
  <input type="file" multiple=multiple id="file" name="files" />
}

最佳答案

Request.Files 返回 HttpFileCollection 类型的一个对象。 https://msdn.microsoft.com/en-us/library/system.web.httpfilecollection(v=vs.110).aspx
为了获取文件中的特定文件,您可以通过索引 Files[0]、Files[1] 或命名的 Files[firstName]、Files[secondName]
使用对象的属性 根据您的代码,您只能使用 Files 对象中的一个文件。

关于c# - 将图像添加到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38286761/

相关文章:

c# - 如何获取像 ReadOnlySpan 这样的 ref 结构的 sizeof?

c# - 如何从服务器端代码反序列化 JSON

asp.net-mvc - ASP.NET MVC 辅助方法(如 Html.DropDownList())是否对输出 HTML 进行编码?

asp.net-mvc - 如何从数据库检索 VarBinary 图像到 MVC View

c# - OrderBy ThenBy - 捕获剩余(相等)项目的最简单方法?

c# - Stripe .net "The signature for the webhook is not present in the Stripe-Signature header."

c# - ASP.NET MVC 2 显示()

asp.net - 当 CustomError 设置为 "On"或 "RemoteOnly"时,运行状况监控不会记录错误

c# - sqlite查询慢,如何优化(使用linq to entities)

asp.net - 如何在不往返的情况下更新实体? (EF 4)