G
G
GetB2014-04-13 18:26:49
JavaScript
GetB, 2014-04-13 18:26:49

What is the correct way to upload a file via AJAX in ASP.NET MVC?

The form:

<form id="fileUpload" action="@Url.Action("AddImage")" method="POST" enctype="multipart/form-data">
            <input id="fileInput" type="file" />
            <input type="submit" value="Upload file" id="btnFileUpload" />
        </form>
    </div>


Controller:
[HttpPost]
        public ActionResult AddImage(HttpPostedFileBase image)
        {
            string fileName = image.FileName;
            image.SaveAs(Path.Combine(HttpContext.Current.Server.MapPath("/Images/"), fileName));
            return View("Index");
        }


JS:
$(document).ready(function () {
    $('#btnFileUpload').click(function () {
        var formData = new FormData();
        var file = $('#fileInput').files[0];
        formData.append("fileInput", file);

        $.ajax({
            url: 'Home/AddImage',
            type: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function () {
                alert("URA");
            }
        });
    });


The controller always gets image = null. What could be the problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
NChervin, 2014-04-19
@GetB

Errors in all three places :)
1. In the form, add the name attribute for the control
2. Code in the controller

[HttpPost]
        public ActionResult AddImage()
        {
            HttpPostedFileBase image = Request.Files["fileInput"];
            
            if (image != null && image.ContentLength > 0 && !string.IsNullOrEmpty(image.FileName))
            {
                string fileName = image.FileName;
                image.SaveAs(Path.Combine(Server.MapPath("Images"), fileName));
            }

            return View("Index");
        }

3. In principle, you can do without a script, everything will go and so, by pressing the button. But if jQuery is already used, then the following is quite enough:
$(document).ready(function () {
    $('#btnFileUpload').click(function() {
        $('#fileUpload').submit(function(event) {
            // обработка событий по отправке формы
        });
    });
});

K
Konstantin Kosyanov, 2016-01-25
@ConstKosyanov

But if you really want to get the file through jQuery, then
var file = $('#fileInput') .get()[0]. files[0];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question