2012-10-10 5 views
3

ASP.NET MVC를 처음 사용했습니다. 일부 이미지 필드 (byte[])가있는 모델이 있습니다.SQL Server 및 ASP.NET MVC를 사용하여 이미지를 필드로 삽입하는 방법

나는 컨트롤러와 뷰도 만들었지 만, 코드를 실행할 때 이미지 필드를 업로드하는 데는 아무 것도 없습니다. . 내 이미지는 내 모델의 일부 필드이며 다른 필드는 문자열입니다.

도와주세요. 컨트롤러와 뷰는 어떻게되어야 하는가?

모델 클래스 :

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> 

는하지만 이미지를 업로드 무엇을 사용하여야한다 ?!

답변

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"); 
    } 
관련 문제