Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Upload File in ASP.NET Core MVC

In this article, you will learn how to upload a file or multiple files in the ASP.NET Core Mvc 3.1 application. The file upload in asp.net core allows the user to browse for and select files to be uploaded, providing a browse button and a text box for entering the filename.

Once, the user has entered the filename in the text box by typing the name or browsing, the SaveAs method of the FileUpload control can be called to save the file to the disk. ASP.NET Core MVC actions support uploading of one or more files using simple model binding.

  • Keep reading on File Upload and Download in ASP.NET C#, Drag and Drop JavaScript File Uploader

File Upload in ASP.NET Core MVC

The following source code will demonstrate to you how to upload files in ASP.Net Core MVC 3.1. Let’s create a new ASP.NET Core MVC application, new FileUploadController, and design an HTML form with a file input control for the Index action:

@{
    ViewData["Title"] = "Home Page";
}

Upload Files

Upload one or more files using this form:

In order to support file uploads, we must specify the enctype as multipart/form-data. The enctype attribute specifies how the form data should be encoded when submitting it to the server. The enctype attribute can be used only if the form method is POST.

The file input element supports uploading multiple files. By removing the multiple attributes on the input element, we can restrict it to support just a single file.

Use of Model Binding

We can access the individual files uploaded to the application through Model Binding using the IFormFile interface. Model Binding in ASP.NET Core MVC maps data from HTTP requests to action method parameters.

IFormFile represents a file that is sent with the HttpRequest and has the following structure:

public interface IFormFile
{
    string ContentType { get; }
    string ContentDisposition { get; }
    IHeaderDictionary Headers { get; }
    long Length { get; }
    string Name { get; }
    string FileName { get; }
    Stream OpenReadStream();
    void CopyTo(Stream target);
    Task CopyToAsync(Stream target, CancellationToken cancellationToken = null);
}

When uploading files using model binding and the IFormFile interface, the action method can accept either a single IFormFile or an IEnumerable representing multiple files.

We can loop through one or more uploaded files, save them to the local file system and then use the files as per our application’s logic:

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace FileUpload.Controllers
{
    public class FileUploadController : Controller
    {
        [HttpPost("FileUpload")]
        public async Task Index(List files)
        {
            long size = files.Sum(f => f.Length);
            var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\\Files\\");
            var filePaths = new List();
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    // full path to file in temp location					
                    var filePath = Path.Combine(basePath, formFile.FileName);
                    filePaths.Add(filePath);

                    using (var stream = new FileStream(filePath, 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 });
        }

    }
}

Download Source Code

Conclusion

I hope you liked this article on file upload in asp.net core. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

The post How to Upload File in ASP.NET Core MVC appeared first on DotNetTec.



This post first appeared on Asp Dot Net Tricks And Tips, Dot Net Coding Tips, Google Maps API Developer, please read the originial post: here

Share the post

How to Upload File in ASP.NET Core MVC

×

Subscribe to Asp Dot Net Tricks And Tips, Dot Net Coding Tips, Google Maps Api Developer

Get updates delivered right to your inbox!

Thank you for your subscription

×