2016-08-27 6 views
3

누구나 도와 주시면 감사하겠습니다. 보기에서 폼에 파일 컨트롤을 입력하고 누군가 그림을 선택하고 양식의 제출 단추를 클릭하면 해당 파일을 응용 프로그램의/Pictures 폴더에 저장해야하며 파일 경로는 SQL 데이터베이스에 저장해야합니다. 문자열 (예 :/Pictures/filename).ASP.NET MVC - 이미지를 업로드하고 데이터베이스에 URL을 저장하는 방법

모델 클래스 부분 :

[Table("Automobil")] 
public partial class Automobil 
{ ..... 
    [Required] 
    [StringLength(30)] 
    public string Fotografija{ get; set; } 
    ...... 

보기 (만들기) 파일 부분 :

@using (Html.BeginForm("Create", "Automobili", FormMethod.Post, new { enctype = "multipart/form-data" })) 

.... 
<div class="form-group"> 
      <div class="editor-field"> 
       @Html.TextBoxFor(model => model.Fotografija, new { type = "file" }) 
       @Html.ValidationMessageFor(model => model.Fotografija, "", new { @class = "text-danger" }) 
      </div> 
     </div> 
.... 

컨트롤러 부분 : 내가 그렇게 사진을 어떻게해야합니까 무엇

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create([Bind(Include = "AutomobilID,Marka,Model,Godiste,Zapremina_motora,Snaga,Gorivo,Karoserija,Fotografija,Opis,Cena,Kontakt")] Automobil automobil) 
    { 
     if (ModelState.IsValid) 
     { 
       db.Automobils.Add(automobil); 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
     } 

     return View(automobil); 
    } 

(Fotografija)은 응용 프로그램 폴더의 Pictures 및 SQL Base의 파일 경로 (예 :/Pictures/filename)에 저장할 수 있습니까?

초보자를 미리 도와 주셔서 감사합니다.

+1

데이터베이스에 전체 경로를 넣지 마십시오. 파일 이름을 넣으십시오. 이렇게하면 포함 된 폴더의 위치를 ​​변경하거나 이름을 바꿀 때 데이터를 변경할 필요가 없습니다. 코드를 올바르게 구성했다고 가정하면 코드를 한 곳에서 변경하면됩니다. –

+0

위 코드를 사용하면 사진에 최대 30 자의 유효성 검증 오류가 표시됩니다. 또한 응용 프로그램에 그림 자체를 저장하지 않습니다. – Oggie

+0

제거 [[StringLength (30)]' – Oluwafemi

답변

1

고유 한 파일 이름을 저장하려는 문자열 유형이 Fotografija 인 것처럼 보입니다. 이 필드를 사용하여 브라우저에서 파일을 가져 오지 않으려 고합니다. 다른 입력 필드를 사용합시다.

@using (Html.BeginForm("Index", "Home", FormMethod.Post, 
                new { enctype = "multipart/form-data" })) 
{ 
    <div class="form-group"> 
     <div class="editor-field"> 
      @Html.TextBoxFor(model => model.Model) 
      @Html.ValidationMessageFor(model => model.Model) 
     </div> 
    </div> 
    <!-- TO DO : Add other form fields also --> 

    <div class="form-group"> 
     <div class="editor-field"> 
      <input type="file" name="productImg" /> 
     </div> 
    </div> 
    <input type="submit" /> 
} 

지금 형 HttpPostedFileBase 또 하나 개의 매개 변수를 가지고 당신의 HttpPost 액션 메소드를 업데이트합니다. 이 매개 변수의 이름은 우리가 추가 된 입력 파일 필드 이름 (productImg)

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create([Bind(Include = "AutomobilID,Marka,Model,Godiste, 
      Zapremina_motora,Snaga,Gorivo,Karoserija,Opis,Cena,Kontakt")] Automobil automobil, 
              HttpPostedFileBase productImg) 
{ 
    if (ModelState.IsValid) 
    { 
     if(productImg!=null) 
     { 
      var fileName = Path.GetFileName(productImg.FileName); 
      var directoryToSave = Server.MapPath(Url.Content("~/Pictures")); 

      var pathToSave = Path.Combine(directoryToSave, fileName); 
      productImg.SaveAs(pathToSave); 
      automobil.Fotografija= fileName; 
     } 

     db.Automobils.Add(automobil); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 

    return View(automobil); 
} 

과 동일해야합니다 당신은 어떤 검증 데이터 주석 장식 (예 : [Required], [MinLength] 등)을 제거해야하는 Fotografija 필드를.

기존 파일의 충돌/덮어 쓰기를 방지하기 위해 고유 한 것으로 저장하기 전에 fileName을 업데이트하는 것이 좋습니다. 당신은 내가 컨트롤러가

+0

나를 도와 주셔서 감사합니다. 나는 그것을 많이 고맙다. 이제 작동합니다. 조금 더 시간이 있다면 Fotografija 속성에 대한 주석없이 지금 무엇을해야하는지 말해 줄 수 있습니까? 대신 productImg에 대한 제한을 설정해야합니다 (어디에 넣어야합니까?). 고마워. – Oggie

+0

'MaxLength'를 유지하여 테이블 열 길이를 제어 할 수 있습니다. 이 속성은 파일 이름을 저장하는 데에만 사용됩니다. – Shyju

+0

다시 한번 감사드립니다. 즐거운 하루 되세요. – Oggie

0

코드는 기본 하나를 고유하게하기 위해 (확장 전) 파일 이름에 날짜 시간 현재 값을 추가 할 수 있습니다 호환되도록 변경하는 방법

// GET: Automobili/Edit/5 
    public ActionResult Edit(int? id) 
    { 
     if (id == null) 
     { 
      return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
     } 
     Automobil automobil = db.Automobils.Find(id); 
     if (automobil == null) 
     { 
      return HttpNotFound(); 
     } 
     return View(automobil); 
    } 

    // POST: Automobili/Edit/5 
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Edit([Bind(Include = "AutomobilID,Marka,Model,Godiste,Zapremina_motora,Snaga,Gorivo,Karoserija,Fotografija,Opis,Cena,Kontakt")] Automobil automobil) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Entry(automobil).State = EntityState.Modified; 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     return View(automobil); 
    } 

위의 코드를 작성 하시겠습니까?

감사합니다.

관련 문제