ASP.NET MVC 화면상에서 파일 업로드 하기

ASP.NET MVC 화면상에서 파일 업로드 하기

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

Upload.js

HomeController

참고 사이트

MVC 파일 업로드

MVC와 Ajax로 파일 업로드

form데이터에 요소를 추가

Pie's Tech Note

생계형 개발자의 메모장

comments powered by Disqus

<!— Html Elements for Search -->
    rss facebook twitter github youtube mail spotify instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora