asp.net - 如何使用 SQL Server 和 ASP.NET MVC 将图像作为字段插入

标签 asp.net asp.net-mvc

我对 ASP.NET MVC 非常陌生。我有一个包含一些图像字段的模型 (byte[])。

我也创建了 Controller 和 View ,但是当我运行代码时没有任何内容 上传图像字段。我的图像是模型的一些字段,其他字段是字符串。

请帮助我。 Controller 和 View 应该如何?

模型类:

  public int Id { get; set; }
  public string Name { get; set; }
  public string Activity { get; set; }
  public string Address { get; set; }
  public string Tel { get; set; }
  public string Work_Hours { get; set; }
  public byte[] img1 { get; set; }
  public byte[] img2 { get; set; }

Controller (创建):

 public ActionResult Create(Shop shop)
    {
        try
        {

            var bytes = new byte[0];
            ViewBag.Mime = "image/png";

            if (Request.Files.Count == 1)
            {
                bytes = new byte[Request.Files[0].ContentLength];
                Request.Files[0].InputStream.Read(bytes, 0, bytes.Length);
                ViewBag.Mime = Request.Files[0].ContentType;
            }

            db.Shop.Add(shop);
            db.SaveChanges();

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

我的观点的所有部分都是这样的:

 <div class="editor-label">
        <%: Html.LabelFor(model => model.Activity) %>
    </div>
    <div class="editor-field">
        <%: Html.EditorFor(model => model.Activity) %>
        <%: Html.ValidationMessageFor(model => model.Activity) %>
    </div>
<div class="editor-label">
        <%: Html.LabelFor(model => model.img2) %>
    </div>
    <div class="editor-field">
        <%: Html.EditorFor(model => model.img2)%>
        <%: Html.ValidationMessageFor(model => model.Shop_img2) %>
    </div>

但是我应该用什么来上传图片呢?!

最佳答案

    @{ Html.BeginForm("Load", "Image", FormMethod.Post, 
        new { enctype = "multipart/form-data" }); }
    <input id="file" type="file" name="file" />
    <input id="submit" type="submit" value="Upload Image" style="display: none;" />
    @{ Html.EndForm(); }

    [HttpPost]
    public ActionResult Load(HttpPostedFileBase file)
    {
        if (file.ContentLength == 0)
            RedirectToAction("LoadImage");

        var fileBytes = new byte[file.ContentLength];
        file.InputStream.Read(fileBytes, 0, file.ContentLength);

        // save fileByptes here...

        return RedirectToAction("Edit");
    }

关于asp.net - 如何使用 SQL Server 和 ASP.NET MVC 将图像作为字段插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12825791/

相关文章:

javascript - 如何将内联 Razor 表达式插入 Javascript

asp.net - 使用 RestSharp 请求带有 Windows 身份验证的 URL

asp.net - 如何将 ASP.Net 表单例份验证 loginUrl 全局化为多种语言?

c# - 在 WCF 服务内部的集线器中连接 SignalR

javascript - 如何修复在 HTML 中工作正常但在 MVC View 中不起作用的搜索选项

asp.net-mvc - 如何设置持久身份验证 :true in IIS and what is the use of it?

asp.net - 防止运行时程序集绑定(bind)到旧程序集

c# - 单击链接时执行客户端脚本

asp.net - System.Web.HttpRequest - ContentLength、TotalBytes 和 InputStream.Length 之间有什么区别?

asp.net - 超出 session 的请求队列限制