2011-06-11 1 views
0

이 뭐가 문제 :의 asp.net MVC 3 - 서버에 파일을 업로드 나는 데이터베이스 모델에 파일 이름을 저장할 수 없습니다

보기

@model GestionWeb.DAL.Client 
@using (Html.BeginForm("Index", "Config", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.LabelFor(model => model.TimeZone) 
    @Html.EditorFor(model => model.TimeZone) 
    @Html.ValidationMessageFor(model => model.TimeZone) 

    @Html.HiddenFor(model => model.ClientId) 
    @Html.LabelFor(model => model.Logo) 
    <input type="file" name="Logo" id="Logo" /> 
    @Html.ValidationMessageFor(model => model.Logo) 
    <input type="submit" value="Upload" /> 
} 

컨트롤러 :

[HttpPost] 
public ActionResult Index(Client client) 
{ 
    if (ModelState.IsValid) 
    { 
     if (Request.Files[0].ContentLength > 0) 
     { 
      HttpPostedFileBase file = Request.Files[0]; 
      string filePath = Path.Combine(HttpContext.Server.MapPath("/Upload/"), Path.GetFileName(file.FileName)); 
      file.SaveAs(filePath); 
      client.Logo = file.FileName; 
     } 
     db.Client.Attach(client); 
     UpdateModel<Client>(client); 
     //db.ObjectStateManager.ChangeObjectState(client, EntityState.Modified); 
     db.SaveChanges(); 

     return RedirectToAction("Index"); 
    } 
    return View(client); 
} 

파일을 쓸 수는 있지만 파일 이름은 데이터베이스에 저장되지 않고 오류가 발생하지 않으며 TimeZone 필드 (및 기타 많은 항목)를 업데이트 할 수 있습니다.

내가 뭘 잘못하고있어? 나는 알아낼 수 없다!

감사합니다.

+0

되지 않음 대답하지만,이를 참조하십시오 - http://stackoverflow.com/questions/4535627/where-is-the-best-place-to-save-images-from-users -upload/4535684 # 4535684 그리고 사용자가 저장 한 파일에 대해 사용자가 제공 한 파일 이름을 사용하여 보안이 중단된다면 걱정할 필요가 없습니다. –

+0

고맙습니다. 위험을 감수 하겠지만, 그 페이지는 제 문제를 해결하지 못합니다. – Santiago

답변

1

문제가 발견되면 client.Logo = "blabla"는 UpdateModel 메소드 뒤에 있어야합니다. 이유는 모르겠지만, 내가 설정 한 client.Logo 값이 UpdateModel 실행 후 지워지지 않기 때문에 이 같은 :

[HttpPost] 
public ActionResult Index(Client client) 
{ 
    if (ModelState.IsValid) 
    { 
     if (Request.Files[0].ContentLength > 0) 
     { 
      HttpPostedFileBase file = Request.Files[0]; 
      string filePath = Path.Combine(HttpContext.Server.MapPath("/Upload/"), Path.GetFileName(file.FileName)); 
      file.SaveAs(filePath); 
     } 
     db.Client.Attach(client); 
     UpdateModel<Client>(client); 
     **client.Logo = file.FileName;** 
     db.SaveChanges(); 

     return RedirectToAction("Index"); 
    } 
    return View(client); 
} 
+0

절대적으로 이것에 주목하십시오! 파일을 업로드 할 때 디렉터리로 업로드 한 다음 데이터베이스 레코드를 만들지 만 파일 확장명을 추가하지는 않은 것과 비슷한 문제가있었습니다. – Crouch

1

직접 작성한 유효한 유효한 파일 이름을 사용해야합니다. 그것은 당신의 문제에 대해 오류를 일으키지 않을 것입니다. 그리고 보안 문제를 피할 수 있습니다.

는 예를 들어, 및 String.format()를 사용하여 파일 이름을 생성 할 수 있습니다

문자열 myGeneratedFileName = 및 String.format ("클라이언트 로고 - {0}", Guid.NewGuid()); string filePath = Path.Combine (HttpContext.Server.MapPath ("/ 업로드 /"), myGeneratedFileName); file.SaveAs (filePath); client.Logo = myGeneratedFileName;

그렇다면 file.SaveAs()에서 예외를 처리하고 싶을 수 있습니다.

+0

고마워,하지만 내 문제는 데이터베이스에 이름을 저장하는 것입니다. 'client.Logo = "myfile";을 사용하면 작동하지 않습니다. – Santiago

1

이름 만 저장되지 않으면 데이터 모델에 문제가있는 것일 수 있습니다. Logo 속성이 유효한 열에 매핑되어 있는지 확인할 수 있습니까? 디자이너에서 테이블을 제거하고 다시 추가하여 매핑 정보를 업데이트 할 수 있습니다.

+0

문제가 발견되면'client.Logo = "blabla"는'UpdateModel' 메소드 다음에 있어야합니다. 이유는 모르겠지만 코드를 디버깅하면 설정 한 'client.Logo' 값이 지워지지 않기 때문에 'UpdateModel' 실행 – Santiago

+0

그러면 자신의 질문에 대한 답을 추가하고 그것을 유효한 것으로 표시해야합니다 :) – SandRock

관련 문제