Author : Guest
Total Views : 487
Posted On : Wed, May 2, 2018
Updated On :

Asynchronous file uploading using jQuery and Asp.net MVC

In this article, we will understand to upload the asynchronously using jQuery and Asp.Net MVC.

HTML

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
 
    <title>Upload</title>
</head>
<body>
    <div class="container">
        <h1>File Uploader</h1>
        <div class="panel panel-success">
            <div class="panel-heading">
                File Upload
            </div>
            <div class="panel-body">
                <input name="file" type="file" id="txtUploadFile" />
            </div>
            <div class="panel-footer">
                <span id="msg"></span>
            </div>
        </div>
    </div>
</body>
</html>

JavaScript

$(document).ready(function () {
    $("#txtUploadFile").change(function (e) {
        var files = e.target.files;
        if (files.length > 0) {
            if (window.FormData !== undefined) {
                var data = new FormData();
                for (var x = 0; x < files.length; x++) {
                    data.append("file" + x, files[x]);
                }
                $.ajax({
                    type: "POST",
                    url: "/Home/UploadFile",
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (result) {
                        if (result) {
                            $("#msg").text("File uploaded successfully!");
                        }
                    },
                    error: function (xhr, status, p3, p4) {
                        var err = "Error " + " " + status + " " + p3 + " " + p4;
                        if (xhr.responseText && xhr.responseText[0] == "{")
                            err = JSON.parse(xhr.responseText).Message;
                        console.log(err);
                    }
                });
            } else {
                alert("Something went wrong! Please try again.");
            }
        }
 
    });
});

Controller-Action

[HttpPost]
public async Task<JsonResult> UploadFile()
{
    bool Status = false;
    try
    {
        foreach (string file in Request.Files)
        {
            var fileContent = Request.Files[file];
            if (fileContent != null && fileContent.ContentLength > 0)
            {
                var stream = fileContent.InputStream;
                var fileName = GetFileName();
                var fileExt = Path.GetExtension(fileContent.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/StaticResource"), fileName + fileExt);
                using (var fileStream = System.IO.File.Create(path))
                {
                    stream.CopyTo(fileStream);
                    Status = true;
                }
            }
        }
    }
    catch {}
    return Json(Status);
}