Upload Multiple File Using Ajax in ASP.NET Core 2.1

Nay mình sẽ xây dựng một chức năng Upload Multiple File Using Ajax in ASP.NET Core 2.1 , nó cũng giống như bạn upload multiple file using Ajax in PHP vậy. 
Đầu tiên cũng là bước khởi động lấy cảm hứng là mở chương trình Visual Studio lên và tạo project thôi

Upload Multiple File Using Ajax in ASP.NET Core 2.1

# Create Project ASP.NET Core 2.1
Bước 1: Trong Visual Studio 2019, Bạn chọn File->New, chọn Project
Bước 2: Chọn Create a new project
Bước 3: Chọn ASP.NET Core Web Application template
Bước 4: Đặt tên Project, chọn Create. 
Bước 5: Select .NET Core, ASP.NET Core 2.1, Chọn Web Application (Model-View-Controller), sau đó bấm Create

Sau khi tạo xong bạn sẽ được một Project , cũng là giờ lúc ta cấu hình nó như sau
+ Mở file Index.cshtml trong Views/Home/Index.cshtml lên và chỉnh sửa, xóa hết code trong file và copy code dưới đây vào

@{
    ViewData["Title"] = "Home Page";
}
<div class="row">
    <h2>Upload File Multiple using ASP Core 2.1</h2>
    <div class="col-md-8">
        <form enctype="multipart/form-data" id="UploadFile">
            @Html.AntiForgeryToken();
            <div class="form-group">
               <input type="file" name="files" multiple class="form-control selectImage" id="images"/>
            </div>
            <div class="form-group">
                <div id="filelist">
                    <!--show proccessbar-->
                </div>
            </div>
            <div class="form-group">
                <input type="submit" name="submit" value="Upload file" class="btn btn-primary"/>
            </div>
        </form>
    </div>
</div>

Trong đoạn code trên bạn cần phải thêm enctype="multipart/form-data" để giúp ta chọn file từ thẻ input
Tạo một <div id="filelist"></div> : dùng để hiển thị các processbar của ta
Okay, Tới phần xử lý đoạn ajax, muốn sử dụng được Ajax bạn cần import file Jquery.min.js vào file nhé:<script src="~/js/jquery.min.js"></script>

$(document).ready(function () {
            /*create array image*/
            var dataImage = [];
            /*create array id processbar*/
            var dataProcessBarID = [];
            $(".selectImage").change(function () {
               var processBar = "";
                var totalfiles = document.getElementById('images').files.length;
                if (totalfiles > 0) {
                    for (var i = 0; i < totalfiles; i++){
                        var nameFile = document.getElementById('images').files[i];
                        dataImage[i] = nameFile;
                        var processID = "processID_" + i;
                        processBar += "<label class=\"label label-primary\">File:" + nameFile.name + "</label><br/><div class=\"progress\">" +
                                    "<div id='"+processID+"' class=\"progress-bar progress-bar-success\" role=\"progressbar\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width:0%\">"+
                                        "0% Complete (success)"+
                                    "</div>"+
                            "</div>";
                        dataProcessBarID[i] = processID;
                    }
                    $("#filelist").html(processBar);
                }

            });
    });

Với đoạn code bên trên, ta bấm chọn file, xem ta đã chọn bao nhiêu file, sau đó ta tạo Array chưa dữ liệu file mà ta đã chọn, bạn có thể xem phần chú thích code bên trên
Sau khi dòng lặp for thực hiện xong, ta hiển thị các processBar ra <div id="filelist"></div>
Tiếp tục với đoạn code tiếp theo:

/*uploadFile*/
        var uploadFile = function (data, processId) {
            if (data.name.match(/.(jpg|jpeg|png|gif|txt)$/i)) {
                var form_data = new FormData();
                /*add file image to form_data*/
                form_data.append("files", data);
                $.ajax({
                    type: 'POST',
                    url: "@Url.Action("UploadFile","Home")",
                    data: form_data,
                    contentType: false,
                    dataType: 'json',
                    processData: false,
                    cache: false,
                    xhr: function () {
                        var xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener("progress", function (evt) {
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                percentComplete = parseInt(percentComplete * 100);
                                $("#" + processId).text(percentComplete + '%  Complete (success) '+data.name);
                                $("#" + processId).css('width', percentComplete + '%');
                            }
                        }, false);
                        return xhr;
                    },
                    success: function (data) {
                        console.log(data);
                    }

                });
            }
            else {
                $("#" + processId).removeClass(" progress-bar-success");
                $("#" + processId).addClass(" progress-bar-danger");
                $("#" + processId).text('0% (fail filname:)'+ data.name);
                $("#" + processId).css('width', '100%');
            }


        }

         /* event submit form upload*/
        $("#UploadFile").submit(function (event) {
            event.preventDefault();
            /*for array dataImage & dataProcessBarID*/
               for (var k = 0; k < dataImage.length; k++){
                    uploadFile(dataImage[k], dataProcessBarID[k]);
               }
        });

Trong đoạn code bên trên, khi ta bấm vào Submit form, nó sẽ for dữ liệu file trong Array ra và uploadFile

FullCode: Index.cshtml

@{
    ViewData["Title"] = "Home Page";
}
<div class="row">
    <h2>Upload Multiple File Using Ajax in ASP.NET Core 2.1</h2>
    <div class="col-md-8">
        <form asp-controller="Home" asp-action="Index" enctype="multipart/form-data" id="UploadFile">
            @Html.AntiForgeryToken();
            <div class="form-group">
               <input type="file" name="files" multiple class="form-control selectImage" id="images"/>
            </div>
            <div class="form-group">
                <div id="filelist">
                    <!--show proccessbar-->
                </div>
            </div>
            <div class="form-group">
                <input type="submit" name="submit" value="Upload file" class="btn btn-primary"/>
            </div>
        </form>
    </div>
</div>
@section Scripts{ 
    <script src="~/js/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            /*create array image*/
            var dataImage = [];
            /*create array id processbar*/
            var dataProcessBarID = [];
            $(".selectImage").change(function () {
               var processBar = "";
                var totalfiles = document.getElementById('images').files.length;
                if (totalfiles > 0) {
                    for (var i = 0; i < totalfiles; i++){
                        var nameFile = document.getElementById('images').files[i];
                        dataImage[i] = nameFile;
                        var processID = "processID_" + i;
                        processBar += "<label class=\"label label-primary\">File:" + nameFile.name + "</label><br/><div class=\"progress\">" +
                                    "<div id='"+processID+"' class=\"progress-bar progress-bar-success\" role=\"progressbar\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\" style=\"width:0%\">"+
                                        "0% Complete (success)"+
                                    "</div>"+
                            "</div>";
                        dataProcessBarID[i] = processID;
                    }
                    $("#filelist").html(processBar);
                }

            });

        /*uploadFile*/
        var uploadFile = function (data, processId) {
            if (data.name.match(/.(jpg|jpeg|png|gif|txt)$/i)) {
                var form_data = new FormData();
                /*add file image to form_data*/
                form_data.append("files", data);
                $.ajax({
                    type: 'POST',
                    url: "@Url.Action("UploadFile","Home")",
                    data: form_data,
                    contentType: false,
                    dataType: 'json',
                    processData: false,
                    cache: false,
                    xhr: function () {
                        var xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener("progress", function (evt) {
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                percentComplete = parseInt(percentComplete * 100);
                                $("#" + processId).text(percentComplete + '%  Complete (success) '+data.name);
                                $("#" + processId).css('width', percentComplete + '%');
                            }
                        }, false);
                        return xhr;
                    },
                    success: function (data) {
                        console.log(data);
                    }

                });
            }
            else {
                $("#" + processId).removeClass(" progress-bar-success");
                $("#" + processId).addClass(" progress-bar-danger");
                $("#" + processId).text('0% (fail filname:)'+ data.name);
                $("#" + processId).css('width', '100%');
            }


        }

         /* event submit form upload*/
        $("#UploadFile").submit(function (event) {
            event.preventDefault();
            /*for array dataImage & dataProcessBarID*/
               for (var k = 0; k < dataImage.length; k++){
                    uploadFile(dataImage[k], dataProcessBarID[k]);
               }
        });

    });
    </script>
}

Ok vậy là xong phần thiết lập Form và Ajax, tiếp theo ta cần cấu hình file HomeController.cs trong thư mục Controllers/HomeController.cs

using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Headers;
using UploadFileMultipleASPCore.Models;

namespace UploadFileMultipleASPCore.Controllers
{
    public class HomeController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        public HomeController(IHostingEnvironment hostingEnvironment)
        {
        
            this._hostingEnvironment = hostingEnvironment;
           
        }
        public IActionResult Index()
        {
            return View();
        }
        /*Upload file image*/
        [HttpPost]
        public async Task<IActionResult> UploadFile(List<IFormFile> files)
        {
            if (ModelState.IsValid)
            {
                var filesPath = $"{this._hostingEnvironment.WebRootPath}/images";
                foreach (var file in files)
                {
                    string ImageName = Path.GetFileName(file.FileName);//get filename
                    var fullFilePath = Path.Combine(filesPath, ImageName);
                    using (var stream = new FileStream(fullFilePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                }
                return Ok(1);
            }
            return Ok(0);

        }

    }
}

Ok xong, bạn có thể chạy thử! chúc các bạn thành công!

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)