ASP.NET MVC 에서 화면에서 파일 업로드 기능을 추가 하는 방법입니다.
방법 1. MVC 기능을 이용한 파일 업로드
Upload.cshtml
@using (Html.BeginForm("Upload", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<input type="file" name="uploadFile" />
<button type="submit">파일 추가</button>
}
HomeController
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(FormCollection formCollection)
{
var fileName = string.Empty;
if (Request != null)
{
HttpPostedFileBase file = Request.Files["uploadFile"];
// 처리
}
return View();
}
※방법 1은 F5(새로고침)할때마다 상기의 액션이 호출되기 때문에 비추합니다.
방법 2. MVC와 Ajax를 활용한 파일 업로드
Upload.cshtml
<div>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<button type="button" onclick="$('#inputFile').click();">파일 선택</button>
<input id="inputFile" type="file" style="display:none;" />
<div id="uploadFile">선택된 파일이 없습니다.</div>
<button id="btnUpload" type="button">파일 추가</button>
}
</div>
<script src="~/xxxx/Upload.js"></script>
<script type="text/javascript">
upload.init();
</script>
Upload.js
var upload = {
uploadFile: null,
init: function () {
this.buttons.init();
},
buttons: {
init: function () {
this.btnInputFile.change();
this.btnUpload.click();
},
btnInputFile: {
change: function () {
$('#inputFile').change(function (e) {
$.each(e.target.files, function () {
page.importFile(this);
});
return false;
});
}
},
btnUpload: {
click: function () {
$('#btnUpload').click(function () {
if (page.uploadFile == null) {
alert('파일을 선택해 주세요.');
return;
}
var $form = $(this).closest('form')
var formData = new FormData($form.get(0));
formData.append("file", page.uploadFile);
$.ajax({
type: 'POST',
url: '/Home/Upload',
data: formData,
contentType: false,
processData: false,
success: function (data) {
if (data.IsSuccess) {
alert('업로드 성공');
} else {
alert('업로드 실패');
}
page.importFileReset();
},
error: function (data) {
alert('업로드 에러');
page.importFileReset();
}
});
return false;
});
}
}
},
importFile: function (file) {
$('#uploadFile').replaceWith('<div id="uploadFile">' + file.name + '</div>');
page.uploadFile = file;
},
importFileReset: function () {
$('#uploadFile').replaceWith('<div id="uploadFile">선택된 파일이 없습니다.</div>');
page.uploadFile = null;
}
}
HomeController
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase file)
{
var fileName = string.Empty;
var model = new JsonResultModel();
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
// 처리
}
return Json(model, JsonRequestBehavior.AllowGet);
}
※ 복수개의 파일을 동시에 업로드할 경우에는 단수에서 복수로 설정을 바꾸면 됩니다.
Upload.cshtml
단수
<input id="inputFile" type="file" style="display:none;" />
복수
<input id="inputFile" type="file" multiple style="display:none;" />
Upload.js
단수
uploadFile: null
----------------------
formData.append("file", page.uploadFile);
----------------------
page.uploadFile = file;
복수
uploadFiles: []
----------------------
$.each(page.uploadFiles, function () {
formData.append("files", this);
});
----------------------
page.uploadFiles.push(file);
HomeController
단수
public ActionResult Upload(HttpPostedFileBase file)
복수
public ActionResult Upload(HttpPostedFileBase[] files)
'개발 > ASP.NET' 카테고리의 다른 글
ASP.NET MVC : 파일 다운로드의 callback 설정하기 (0) | 2019.01.24 |
---|---|
XML 형식의 string 문자열을 파싱하기 (0) | 2019.01.23 |
ASP.NET MVC : CSV 파일을 작성해서 다운로드 하기 (0) | 2019.01.23 |
개인적으로 자주 쓰는 LINQ 샘플 (0) | 2019.01.23 |
CSV 파일 출력시에 마지막 행에 NULL 문자열이 삽입되는 문제(byte[] 변환 문제) (0) | 2019.01.23 |
댓글