0

데이터를 모델에 바인딩하고 DB에 추가하는 ActionResult가 있습니다. 이제 내가 원하는 것은 파일 업 로더를 가지고 ActionResult가 파일을 저장하고 FileName을 DB에 추가하는 것입니다 (나중에 파일/이미지를 표시 할 수 있습니다). 가장 좋은 방법은 무엇입니까? 여기에 내가 (그것은 파일을 저장하지만, EF가 얼마나 지능 확실하지 메신저 및 데이터 유형이 얼마나 복잡한 수 있습니다) 지금까지 무엇을 가지고 있습니다 :MVC3/EF4.1 HttpPostedFileBase를 모델링하여 DB에 추가하기

모델 클래스 :

public class Annonce 
{ 
    public int Id { get; set; } 
    public string Company { get; set; } 
    public string Size { get; set; } 
    public IEnumerable<HttpPostedFileBase> FileUpload { get; set; } 
} 

뷰 (사용 mircosoft.web.helpers) :

@using (Html.BeginForm("Create", "Annonce", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.ValidationSummary(true) 
    <fieldset> 
     <legend>Annonce</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Company) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Company) 
      @Html.ValidationMessageFor(model => model.Company) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Size) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Size) 
      @Html.ValidationMessageFor(model => model.Size) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.FileUpload) 
     </div> 
     <div class="editor-field"> 
@FileUpload.GetHtml(uploadText: "Opret") 
     </div> 
    </fieldset> 

컨트롤러 :

[HttpPost] 
    public ActionResult Create(Annonce annonce) 
    { 
     if (ModelState.IsValid) 
     {     
      //System.IO stuff 
      foreach (var file in annonce.FileUpload) 
      { 
       if (file.ContentLength > 0) 
       { 
        var fileName = Path.GetFileName(file.FileName); 
        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); 
        file.SaveAs(path); 

       } 
      } 
      //Database stuff 
      db.Annoncer.Add(annonce); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(annonce); 
    } 

이 파일을 잘 저장 . 이제 제가 원했던 것은 file.FileName이 db에있는 상점입니다. 처음에는 EF가 단순히 파일 또는 파일 이름을 model.FileUpload에서 db로 바인드하지만. 하지만 데이터 유형이 너무 복잡하다고 생각합니까? 그래서 나는 list<HttpPostedFileBase>을 만들고 거기에 file.FileName을 추가한다고 생각합니까? 또는 모든 파일 이름이 참조 ID가있는 문자열로 저장되는 전체 엔티티/테이블을 새로 만들 수 있습니까? 제안 사항이 있으십니까?

답변

1

실제 파일 내용을 데이터베이스에 저장하지 않으려한다고 생각합니다. asp.net 당신이 App_Data 폴더에서 파일을 제공하는 것을 허용하지 않습니다 때문에, 당신은 이후에 저장 경로를 조정해야

public class AnnonceFile 
{ 
    public string filename {get;set;} 
} 

public class Annonce 
{ 
    public int Id { get; set; } 
    public string Company { get; set; } 
    public string Size { get; set; } 
    public ICollection<AnnonceFile> Filenames{ get; set; } 
} 


     //System.IO stuff 
     foreach (var file in files) 
     { 
      if (file.ContentLength > 0) 
      { 
       var fileName = Path.GetFileName(file.FileName); 
       var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); 
       file.SaveAs(path); 
       annonce.Filenames.Add(new AnnonceFile {filename = path}); 

      } 
     } 
     //Database stuff 
     db.Annoncer.Add(annonce); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
  1. : 그래서 내가 좋아하는 일을 할 것입니다.
  2. public ICollection<string> Filenames은 아이디어를 제공하기위한 것이지만, 아마도 ICollection<FileEntity> Files에서 변경해야 할 것입니다.
+0

정확히, DB에 저장된 파일을 원하지 않습니다. 파일 이름뿐입니다. 하지만 예 ICollection 실 거예요, 파일 및 물건을 저장하려면 HttpPostedFileBase가 필요합니다. IEnumerable 대신 ICollection을 사용하면 어떤 차이가 있는지 모르겠습니까? 또는 FileUpload와 함께 Filenames라는 또 다른 속성을 만들 것을 제안 하시겠습니까? –

+1

문자열이 아니라 개체의 집합이어야합니다. Annonce 엔티티와 업로드 된 파일 사이에 1 : n 관계가 있습니다. –

+0

예. 알겠습니다. 더 정확한 코드를 제공 할 수 있습니까? –