2011-12-18 4 views
37

ASP.NET MVC에서 파일을 업로드 할 때 문제가 있습니다. 내 코드는 다음과 같습니다 :HttpPostedFileBase는 ASP.NET MVC에서 항상 null을 반환합니다.

보기 :

@{ 
    ViewBag.Title = "Index"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

<h2>Index2</h2> 
@using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <input type="file" /> 
    <input type="submit" /> 
} 

컨트롤러 :

[HttpPost] 
public ActionResult FileUpload(HttpPostedFileBase uploadFile) 
{ 
    if (uploadFile != null && uploadFile.ContentLength > 0) 
    { 
     string filePath = Path.Combine(Server.MapPath("/Temp"), Path.GetFileName(uploadFile.FileName)); 
     uploadFile.SaveAs(filePath); 
    } 
    return View(); 
} 

그러나 UploadFile로는 항상 null를 돌려줍니다. 누구나 알아낼 수 있습니까 ??

답변

94
@{ 
    ViewBag.Title = "Index"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

<h2>Index2</h2> 
@using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <input type="file" name="uploadFile"/> 
    <input type="submit" /> 
} 

당신은 ASP.net의 MVC에 바인딩 작업을 모델링하고
도 있는지 확인하기 위해을 UploadFile로하는 입력 유형의 파일에 이름을 제공해야합니다 귀하의 입력 형식 파일과 인수 이름HttpPostedFileBase을의의 이름 동일합니다.

+0

와우와 감사 버전을 사용해야 함을 의미한다. 이 MVC에 대해서는 전혀 몰랐습니다. ASP.NET MVC를 처음 접했습니다. 감사. –

+36

필드 이름을 놓치지 않았지만 양식 정의에서 enctype 매개 변수가 누락되어 'null'문제가 발생했습니다. 예를 들어 주셔서 감사합니다. – niallsco

+0

@ dotnetstep thanks – anpatel

0

또 다른 시나리오가있을 수 있습니다. 제 경우에는 MVC 뷰에서 스크립트 태그를 직접 렌더링했기 때문에 IE에서 문제가 발생했습니다.

보기

올바른 코드는 다음과 같아야합니다

@section scripts 
{ 
    <script> 
     $(document).ready(function() { 
      $('.fileinput').fileinput(); 
... 
} 
6

나는

그것은 정말 ...이 주제에 대한 온라인에 게시 된 솔루션의 대부분을했지만, 더 나은 대신 해결 방법을 사용하는 발견했다 HttpPostedFileBase 및/또는 HttpPostedFile은 항상 null이었습니다. HttpContext.Request.Files 컬렉션을 사용하면 번거 로움없이 작업하는 것처럼 보였습니다.

if (HttpContext.Request.Files.AllKeys.Any()) 
     { 
      // Get the uploaded image from the Files collection 
      var httpPostedFile = HttpContext.Request.Files[0]; 

      if (httpPostedFile != null) 
      { 
       // Validate the uploaded image(optional) 

       // Get the complete file path 
       var fileSavePath =(HttpContext.Server.MapPath("~/UploadedFiles") + httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf(@"\"))); 

       // Save the uploaded file to "UploadedFiles" folder 
       httpPostedFile.SaveAs(fileSavePath); 
      } 
     } 

는 위의 예에서 나는 첫 번째 파일을 잡아하지만 모든 파일을 저장하는 컬렉션하지만 반복의 문제이다.

<input type="file" name="file1" /> 
3

,이 있었다 이 특정 사용자에 대한 대답이 아니라는 것을 지적하고 싶습니다. HTML requires that the form tag has an enctype attribute with the value multipart/form-data. A 물론 속성과 값이 모두 정확해야합니다. MVC에 대한

,이 beginform를 사용하는 경우, 당신이 아주 많이 ... htmlAttributes 매개 변수

+3

Damm, 제 경우에는 HttpPostedFileBase 대신 HttpPostedFile을 사용했습니다 .. 프로그래머 오류 :/ –

+0

Samuel이 내 하루를 저장했습니다! 그것이 http://stackoverflow.com/a/24911221/2346618에 설명되어 있지만 서명에서 기본 클래스 인 HttpPostedFileBase를 사용하는 것이 바보 같다고 생각합니다. 객체 지향 프로그래밍에서 기본 클래스는 구체적인 클래스의 구성을 돕는 데 사용되며 인터페이스는 프로토콜에 사용됩니다. IHttpPostedFile과 같은 인터페이스를 사용하면 오류가 발생하기 쉬운 IMO가 줄어 듭니다. –

0

동안 :

<input type="file" name="file1" id="file1" /> 

soultion이 ID를 제거하는 것이 었습니다 :

문제가 id 속성으로이었다 내 시나리오에서는 HTH

관련 문제