Doctor
Doctor

Reputation: 168

How to insert image as a field using SQL Server and ASP.NET MVC

I'm very new to ASP.NET MVC. I have a model that has some image fields (byte[]).

I have created the controller and view as well, but when I run the code there is nothing to upload the image field. My images are some fields of my model and other fields are string.

Please help me. How the controller and view should be?

Model class :

  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 (Create) :

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

All parts of my view is like this :

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

But what shall I use for uploading images?!

Upvotes: 3

Views: 3432

Answers (1)

andleer
andleer

Reputation: 22568

    @{ 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");
    }

Upvotes: 1

Related Questions