2013-02-27 4 views
10

사용자가 파일을 업로드하고 데이터베이스에 저장할 수있는 기능을 양식에 제공하고 싶습니다. 이 작업은 ASP.NET MVC에서 어떻게 수행됩니까?ASP.NET MVC로 데이터베이스에 파일 업로드

내 모델 클래스에 쓸 데이터 유형은 무엇입니까? Byte[]으로 시도했지만, 스캐 폴딩 중에 솔루션은 해당 뷰에서 해당 HTML을 생성 할 수 없습니다.

이러한 사례는 어떻게 처리됩니까?

답변

31

모델에 byte[]을, 뷰 모델에 HttpPostedFileBase을 사용할 수 있습니다. 다음

public class MyViewModel 
{ 
    [Required] 
    public HttpPostedFileBase File { get; set; } 
} 

과 : 예를 들어

public class HomeController: Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new MyViewModel(); 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     if (!ModelState.IsValid) 
     { 
      return View(model); 
     } 

     byte[] uploadedFile = new byte[model.File.InputStream.Length]; 
     model.File.InputStream.Read(uploadedFile, 0, uploadedFile.Length); 

     // now you could pass the byte array to your model and store wherever 
     // you intended to store it 

     return Content("Thanks for uploading the file"); 
    } 
} 

마지막으로보기에 :

@model MyViewModel 
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <div> 
     @Html.LabelFor(x => x.File) 
     @Html.TextBoxFor(x => x.File, new { type = "file" }) 
     @Html.ValidationMessageFor(x => x.File) 
    </div> 

    <button type="submit">Upload</button> 
} 
+0

안녕하세요, 멋진,하지만 절대 멍청한 놈으로, 어디에 가장 좋은 장소가 될 것입니다 예를 들어, 사이트 관리자가 사용자가 다운로드 할 수있는 파일 (응용 프로그램 .exe 파일)을 업로드하는 것을 허용하려는 경우 파일을 저장할 수 있습니까? – MoonKnight