반응형

asp.net MVC4 프레임 워크에서 파일을 업로드 받기 위한 코드입니다.

먼저 HTML 쪽에 아래와 같이 파입 업로드 폼을 만들어줍니다.

<form action="Upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit">
</form>

 

그 다음 컨트롤러에서 웹페이지에서 POST된 파일을 받아 저장합니다.

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}

 

여러 파일을 전송 받을 때는 아래와 같이 변경 해줍니다.

<form action="Upload" method="post" enctype="multipart/form-data">
<input type="file" name="files" id="file1">
<input type="file" name="files" id="file2">
<input type="submit">
</form>
[HttpPost]
public ActionResult Upload(IEnumerable<httppostedfilebase> files)
{
if (ModelState.IsValid)
{
foreach(var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(path);
}
}
}
return RedirectToAction("Index");
}

출처: https://kindtis.tistory.com/516

반응형

+ Recent posts