Free Web Development Online Tutorials, Learn to Code
Asp.net Core MVC file upload complete example, Uploading multiple images in Asp.net Core C#

ASP.NET Core MVC File Upload Example

In this tutorial you will learn how to upload file in asp.net core, You will also learn how to retrieve those files and delete from folder under wwwroot.

asp.net core mvc file uploading example

File Uploading Example in Asp.Net Core

First we design a form in razor view that will allow us to browse and upload one or multiple images from local machine.

Form design in Razor View, Note: If you specify multiple in input file field, which means it will allow multiple files to be selected and uploaded.

<form method="post" enctype="multipart/form-data" asp-controller="FileUpload" asp-action="index">
<div class="form-group">
    <div class="col-md-10">
        <p>Upload one or more files using this form:</p>
        <input type="file" name="files" multiple />
    </div>
</div>
<div class="form-group">
    <div class="col-md-10">
        <input type="submit" value="Upload" />
    </div>
</div>
</form>

Add Middleware Service in Startup

You need to add following Middleware Service reference in ConfigureServices method of Startup.cs file. In your ConfigureService method there may be many other services already added, so just add IFileProvider Service also.

using Microsoft.Extensions.FileProviders;
using System.IO;

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IFileProvider>(new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));
    services.AddMvc();
}

Get file path in asp.net Core

To get folder reference in Asp.net Core Controller you need to Add IHostingEnvironment in Controller with DI

Now you need the folder reference where you want to save all uploaded image files, and to get that you need an instance of IHostingEnvironment, so in controller constructor we create the instance using dependency injection

private readonly IHostingEnvironment _hostingEnvironment;

public fileuploadController(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
}

File Upload Controller Code

Finally we write the controller code where we process the files posted from image upload form in razor view.

Note: while creating FileStream object pass file name with folder Path, if you pass only folder Path in FileStream, You may get UnauthorizedAccessException while uploading file in asp.net core application.

using Microsoft.Extensions.FileProviders;
using System.IO;

[HttpPost("FileUpload")]
public async Task<IActionResult> index(List<IFormFile> files)
    {
    if (files == null || files.Count == 0)
        return Content("file not selected");
    long size = files.Sum(f => f.Length);
    var filePaths = new List<string>();
    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            // full path to file in temp location
            var filePath = Path.Combine(_hostingEnvironment.WebRootPath, "userimages");

            filePaths.Add(filePath); 

            var fileNameWithPath = string.Concat(filePath,"\\",formFile.FileName);

            using (var stream = new FileStream(fileNameWithPath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }
    // process uploaded files
    // Don't rely on or trust the FileName property without validation.
    return Ok(new { count = files.Count, size, filePaths });
    }

Hope you have understood the implementation of file uploading in asp.net core

Now probably you would like to know how to retrieve and display any uploaded file from any folder under wwwroot in asp.net core!

Comment
Name
Email
Website
Subscribe