3

我对 ASP.NET MVC 很陌生。我有一个模型,它有一些图像字段 ( byte[])。

我也创建了控制器和视图,但是当我运行代码时,没有任何东西可以上传图像字段。我的图像是我模型的某些字段,而其他字段是字符串。

请帮我。控制器和视图应该如何?

模型类:

  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; }

控制器(创建):

 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>

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

4

1 回答 1

1
    @{ 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");
    }
于 2012-10-10T20:03:44.383 回答