In this article I will explain with an example, how to upload files using Web API in ASP.Net Core MVC.
This article will illustrate how to send (upload) files by calling the Web API using jQuery AJAX in ASP.Net Core MVC.
 
 

Namespaces

You will need to import the following namespaces.
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
 
 

Web API Controller

In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.
Now from the Add New Item window, choose the API Controller – Empty option as shown below.
ASP.Net Core MVC: Upload Files using Web API
 
Then give it a suitable name and click Add.
 

Action method for uploading the Files

The next step is to add an Action Method to the Web API Controller.
Inside this Action method, first the Folder (Directory) where the Files will be saved is created inside the www Folder using IHostingEnvironment interface if it does not exists.
Note: For more details about IHostingEnvironment interface, please refer Using IHostingEnvironment in ASP.Net Core.
 
Then the Name of the File is read from Request.Form collection and the File is read from the Request.Form.Files collection and saved in the Folder (Directory) created earlier using the FileStream class.
Finally, an OK response along with the name of the File is returned to the Client which confirms successful upload of the File.
[Route("api/[controller]")]
[ApiController]
public class FileAPIController : ControllerBase
{
    private IHostingEnvironment Environment;
 
    public FileAPIController(IHostingEnvironment _environment)
    {
        Environment = _environment;
    }
 
    [Route("UploadFiles")]
    [HttpPost]
    public IActionResult UploadFiles()
    {
        //Create the Directory.
        string path = Path.Combine(this.Environment.WebRootPath, "Uploads\\");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
 
        //Fetch the File.
        IFormFile postedFile = Request.Form.Files[0];
 
        //Fetch the File Name.
        string fileName = Request.Form["fileName"] + Path.GetExtension(postedFile.FileName);
 
        //Save the File.
        using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
        {
            postedFile.CopyTo(stream);
        }
 
        //Send OK Response to Client.
        return Ok(fileName);
    }
}
 
 

Controller

Now you will need to add one empty Controller along with a View. The View will be used for calling the Web API Controller’s method using jQuery AJAX.
The Controller consists of an empty Action method which simply returns the View.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
 
 

View

HTML Markup

The View consists of an HTML TextBox, an HTML FileUpload element, a Button and an HTML5 Progress element for displaying the progress of the uploading File and an HTML SPAN element.
The Upload Button has been assigned a jQuery Click event handler.
When the Upload Button is clicked, the File is read from the HTML FileUpload element and added to an HTML5 FormData JavaScript object and then the File is uploaded using XmlHttpRequest (XHR).
A Progress event handler is attached to the XmlHttpRequest (XHR), which displays the progress of the File being uploaded using the HTML5 Progress element.
The Name of the File is fetched from the TextBox and is added to the FormData object along with the File.
Finally, the received Name of the uploaded File is displayed in an HTML SPAN element.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <table>
        <tr>
            <td>Name: </td>
            <td><input type="text" id="fileName" /></td>
        </tr>
        <tr>
            <td>File: </td>
            <td><input type="file" id="file" /></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="button" id="btnUpload" value="Upload" /></td>
        </tr>
        <tr>
            <td colspan="2"><progress id="fileProgress" style="display: none"></progress></td>
        </tr>
    </table>
    <hr />
    <span id="lblMessage" style="color: Green"></span>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        $("body").on("click""#btnUpload"function () {
            var formData = new FormData();
            formData.append("fileName", $("#fileName").val());
            formData.append("file", $("#file")[0].files[0]);
            $.ajax({
                url: '/api/FileAPI/UploadFiles',
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (fileName) {
                    $("#fileProgress").hide();
                    $("#lblMessage").html("<b>" + fileName + "</b> has been uploaded.");
                },
                xhr:function () {
                    var fileXhr = $.ajaxSettings.xhr();
                    if (fileXhr.upload) {
                        $("progress").show();
                        fileXhr.upload.addEventListener("progress"function (e) {
                            if (e.lengthComputable) {
                                $("#fileProgress").attr({
                                    value: e.loaded,
                                    max: e.total
                                });
                            }
                        }, false);
                    }
                    return fileXhr;
                }
            });
        });
    </script>
</body>
</html>
 
 

Screenshot

ASP.Net Core MVC: Upload Files using Web API
 
 

Browser Compatibility

The above code has been tested in the following browsers.
Microsoft Edge   FireFox  Chrome  Safari  Opera
* All browser logos displayed above are property of their respective owners.
 
 

Downloads