2012-03-18 2 views
2

파일을 업로드하려고하지만 enctype = "multipart/form-data"를 사용하는 asp.net에서 응용 프로그램을 개발 중입니다. 양식 모음이 비어있을 때 나는 enctype을 사용하지 않는다. 폼 콜렉션은 파일 업로드 이름이지만 Request.Files.count = 0이다. 나는 파일 업로드와 폼 콜렉션에서 업로드 파일의 이름을 얻고 싶다. 어떤 해결책?양식 컬렉션이 비어 있습니다. 파일 업로드에 enctype을 사용하는 경우

답변

0

다음은 나를 위해 잘 작동 : 파일 입력 파일을 가져 컨트롤러 액션 이후에 사용됩니다 name이 있어야합니다

@using (Html.BeginForm("someaction", "somecontroller", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <input type="file" name="file" /> 
    <button type="submit">Upload</button> 
} 

공지있다. Request.File.Count = 0을 얻고 있다는 사실은 입력 필드에 이름을 제공하지 않았 음을 나타내는 매우 강력한 표시입니다.

과 조치 :

[HttpPost] 
public ActionResult SomeAction(HttpPostedFileBase file) 
{ 
    if (file != null && file.ContentLength > 0) 
    { 
     var filename = Path.GetFileName(file.FileName); 
     filename = Path.Combine(Server.MapPath("~/uploads"), filename); 
     file.SaveAs(filename); 
    } 
    return View(); 
} 

하고 FormCollection (나는 권장하지 것이다)를 사용하기를 원한다면 :

[HttpPost] 
public ActionResult SomeAction() 
{ 
    var file = Request.Files["file"]; 
    if (file != null && file.ContentLength > 0) 
    { 
     var filename = Path.GetFileName(file.FileName); 
     filename = Path.Combine(Server.MapPath("~/uploads"), filename); 
     file.SaveAs(filename); 
    } 
    return View(); 
} 

또한 following blog post을 체크 아웃 할 수 있습니다. 다음 코드

1

체크 아웃 :

@using (Html.BeginForm("Create", "Employees", FormMethod.Post,new{ enctype="multipart/form-data"})) 
{ 
    @Html.TextBoxFor(model => model.Name) 

    @Html.TextBoxFor(model => model.Resume, new { type = "file" }) 

    <p> 
    <input type="submit" value="Save" /> 
    </p> 
@Html.ValidationSummary() 
} 

추가 컨트롤러의 당신의 각 작업에서 다음 코드,

[HttpPost] 
public ActionResult Create(EmployeeViewModel viewModel) 
{ 
     if (Request.Files.Count > 0) 
     { 
      foreach (string file in Request.Files) 
      { 
       string pathFile = string.Empty; 
       if (file != null) 
       { 
        string path = string.Empty; 
        string fileName = string.Empty; 
        string fullPath = string.Empty; 
        path = AppDomain.CurrentDomain.BaseDirectory + "directory where you want to upload file";//here give the directory where you want to save your file 
        if (!System.IO.Directory.Exists(path))//if path do not exit 
        { 
         System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "directory_name/");//if given directory dont exist, it creates with give directory name 
        } 
        fileName = Request.Files[file].FileName; 

        fullPath = Path.Combine(path, fileName); 
        if (!System.IO.File.Exists(fullPath)) 
        { 

         if (fileName != null && fileName.Trim().Length > 0) 
         { 
          Request.Files[file].SaveAs(fullPath); 
         } 
        } 
       } 
      } 
     } 
} 
:

코드에 따라 뷰의 형태로 인코딩 유형을 추가

나는 asssumed 경로는 디렉토리의 디렉토리에있을 것입니다 ... 당신은 파일을 저장하고자하는 자신의 경로를 줄 수 있습니다

관련 문제