2012-03-16 3 views
0

아래와 같은 상황이 발생하면 성공합니다. 이미지 업로드를 처리하고 db에 저장합니다. 이 코드를 염두에두면 여러 이미지 업로드를 구현할 수 있습니다. 감사합니다.mvc3에서 복수 이미지 업로드

우선 먼저.

PropertyViewModel.cs 

... 
public byte[] ImageData { get; set; } 
public string ImageMimeType { get; set; } 

public PropertyViewModel(Property x) 
{ 
    .... 
    ImageData = x.ImageData; 
    ImageMimeType = x.ImageMimeType; 
} 

public void ToDomainModel(Property x) 
{ 
    .... 
    x.ImageData = ImageData; 
    x.ImageMimeType = ImageMimeType; 
} 

지금 Create.cshtml 면도기 페이지

@using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    ... 
    <input type="file" name="Image"/> 
} 

}

컨트롤러가 처리 할 수있는 요청을 형성

[HttpPost] 
public ActionResult Create(PropertyViewModel newProperty, HttpPostedFileBase image) 
     { 
      if (ModelState.IsValid) 
      { 
       if (image != null) 
       { 
        newProperty.ImageMimeType = image.ContentType; 
        newProperty.ImageData = new byte[image.ContentLength]; 

        image.InputStream.Read(newProperty.ImageData, 0, image.ContentLength); 
       } 
       using (session...) 
       { 
        using (...begin transaction) 
        { 
         MyDomain.Property model = new MyDomain.Property(); 
         newProperty.ToDomainModel(model); 
         ..session save model 
         .. commiting session 
        } 
       } 
       return RedirectToAction("Index"); 
      } 
      else 
      { 
       return View(newProperty); 
      } 
     } 

답변

0
@using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    ... 
    <input type="file" name="Image"/> 
    <input type="file" name="Image"/> 
    <input type="file" name="Image"/> 
    <input type="file" name="Image"/> 
} 

또는 브라우저가 HTML5를 지원하는 경우 여러 선택할 수 있습니다 업로드 된 파일 대화 : 다음

@using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    ... 
    <input type="file" name="Image" multiple="multiple"/> 
} 

과 :

public ActionResult Create(PropertyViewModel newProperty, IEnumerable<HttpPostedFileBase> image) 
+0

당신을 감사 훌륭한 이잖아. 이 뷰 모델을 염두에두고 편집 ​​작업을 구현하는 방법은 무엇입니까? 편집 동작 중 일부 ID를 기반으로 모든 이미지를로드합니다. 감사합니다. – BobRock

+0

'IEnumerable Image {get; 세트; }'속성을 뷰 모델에 직접 추가하고 두 번째 작업 인수를 제거합니다. –

+0

그런 다음 domain 속성을 변경해야합니까? 지금 그것의 --------- 공용 가상 바이트 [] ImageData { get {return _ImageData; } 세트 { if (_ImageData == value) 반환; _ImageData = value; } } 공개 가상 문자열 ImageMimeType { get {return _ImageMimeType; } 세트 { if (_ImageMimeType == value) 반환; _ImageMimeType = value; } } – BobRock