ASP. NET Core Method for uploading and saving single and multiple files to the server

  • 2021-11-13 01:24:45
  • OfStack

Foreword:

In our daily development, it is a very common function to upload and save related files such as pictures, videos, audio and documents to the server. Today, we mainly record two ways commonly used in our development for direct use, and hope to help students in need!

1. Configure static files in ASP. NET Core:

Brief overview:

In ASP. NET Core application, static resource files need to be configured to provide direct use to clients.

Please refer to the official document for details:
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

Simple configuration, providing files in Web root directory:

Call the UseStaticFiles method configuration in Startup. Configure:


public void Configure(IApplicationBuilder app)
{
  app.UseStaticFiles();
}

2. File server and application configuration (IIS, Kestrel):

For details, please refer to the official documents:
https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1#server-and-app-configuration

Multipart text length limit:

MultipartBodyLengthLimit sets the length limit for each multipart body. InvalidDataException is thrown when parsing parts of the form that exceed this limit. The default value is 134,217,728 (128 MB). Customize this limit using Startup. ConfigureServices settings in MultipartBodyLengthLimit:


public void ConfigureServices(IServiceCollection services)
{
  services.Configure<FormOptions>(options =>
  {
    // Set the limit to 256 MB
    options.MultipartBodyLengthLimit = 268435456;
  });
}

Kestrel Maximum Request Body Size:

For Kestrel-hosted applications, the default maximum request body size is 30,000,000 bytes, which is approximately 28.6 MB. Customize restrictions using the MaxRequestBodySize Kestrel server options:


public static IHostBuilder CreateHostBuilder(string[] args) =>
  Host.CreateDefaultBuilder(args)
    .ConfigureKestrel((context, options) =>
    {
      // Handle requests up to 50 MB
      options.Limits.MaxRequestBodySize = 52428800;
    })
    .ConfigureWebHostDefaults(webBuilder =>
    {
      webBuilder.UseStartup<Startup>();
    });

IIS content length limit:

The default request limit (maxAllowedContentLength) is 30,000,000 bytes, approximately 28.6 MB. Customize this restriction in the web. config file:


<system.webServer>
 <security>
  <requestFiltering>
   <!-- Handle requests up to 50 MB -->
   <requestLimits maxAllowedContentLength="52428800" />
  </requestFiltering>
 </security>
</system.webServer>

3. Single file upload:


using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace FileUploadManage.Controllers
{
  /// <summary>
  ///  Universal upload service class for pictures, videos, audio, documents and other related files 
  /// </summary>
  public class FileUploadController : Controller
  {
    private static IHostingEnvironment _hostingEnvironment;

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

    /// <summary>
    ///  Single file upload 
    /// </summary>
    /// <returns></returns>
    public JsonResult SingleFileUpload()
    {
      var formFile = Request.Form.Files[0];// Get the file sent by the request 
      var currentDate = DateTime.Now;
      var webRootPath = _hostingEnvironment.WebRootPath;//>>> Equivalent to HttpContext.Current.Server.MapPath("") 

      try
      {
        var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/";

        // Create a daily storage folder 
        if (!Directory.Exists(webRootPath + filePath))
        {
          Directory.CreateDirectory(webRootPath + filePath);
        }

        if (formFile != null)
        {
          // File suffix 
          var fileExtension = Path.GetExtension(formFile.FileName);// Get file format, extension name 

          // Determine file size 
          var fileSize = formFile.Length;

          if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
          {
            return new JsonResult(new { isSuccess = false, resultMsg = " Uploaded files cannot be larger than 10M" });
          }

          // Saved file name ( Name by name and save time )
          var saveName = formFile.FileName.Substring(0, formFile.FileName.LastIndexOf('.'))+"_"+currentDate.ToString("HHmmss")+ fileExtension;

          // File saving 
          using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
          {
            formFile.CopyTo(fs);
            fs.Flush();
          }

          // Full file path 
          var completeFilePath = Path.Combine(filePath, saveName);

          return new JsonResult(new { isSuccess = true, returnMsg = " Upload succeeded ", completeFilePath = completeFilePath });
        }
        else
        {
          return new JsonResult(new { isSuccess = false, resultMsg = " Upload failed, uploaded file information not detected ~" });
        }

      }
      catch (Exception ex)
      {
        return new JsonResult(new { isSuccess = false, resultMsg = " File save failed, exception message is: " + ex.Message });
      }
    }

  }
}

4. Upload multiple files:


using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Internal;

namespace FileUploadManage.Controllers
{
  /// <summary>
  ///  Universal upload service class for pictures, videos, audio, documents and other related files 
  /// </summary>
  public class FileUploadController : Controller
  {
    private static IHostingEnvironment _hostingEnvironment;

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

    /// <summary>
    ///  Multiple file upload 
    /// </summary>
    /// <param name="formCollection"> Form collection value </param>
    /// <returns> File information stored by the server </returns>

    public JsonResult MultiFileUpload(IFormCollection formCollection)
    {
      var currentDate = DateTime.Now;
      var webRootPath = _hostingEnvironment.WebRootPath;//>>> Equivalent to HttpContext.Current.Server.MapPath("") 
      var uploadFileRequestList = new List<UploadFileRequest>();
      try
      {
        //FormCollection Convert to FormFileCollection
        var files = (FormFileCollection)formCollection.Files;

        if (files.Any())
        {
          foreach (var file in files)
          {
            var uploadFileRequest = new UploadFileRequest();

            var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/";

            // Create a daily storage folder 
            if (!Directory.Exists(webRootPath + filePath))
            {
              Directory.CreateDirectory(webRootPath + filePath);
            }

            // File suffix 
            var fileExtension = Path.GetExtension(file.FileName);// Get file format, extension name 

            // Determine file size 
            var fileSize = file.Length;

            if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
            {
              continue;
            }

            // Saved file name ( Name by name and save time )
            var saveName = file.FileName.Substring(0, file.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension;

            // File saving 
            using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
            {
              file.CopyTo(fs);
              fs.Flush();
            }

            // Full file path 
            var completeFilePath = Path.Combine(filePath, saveName);

            uploadFileRequestList.Add(new UploadFileRequest()
            {
              FileName = saveName,
              FilePath = completeFilePath
            });
          }
        }
        else
        {
          return new JsonResult(new { isSuccess = false, resultMsg = " Upload failed, uploaded file information not detected ~" });
        }
      }
      catch (Exception ex)
      {
        return new JsonResult(new { isSuccess = false, resultMsg = " File save failed, exception message is: " + ex.Message });
      }

      if (uploadFileRequestList.Any())
      {
        return new JsonResult(new { isSuccess = true, returnMsg = " Upload succeeded ", filePathArray = uploadFileRequestList });
      }
      else
      {
        return new JsonResult(new { isSuccess = false, resultMsg = " The network dozed off and the file saving failed " });
      }
    }

  }

  /// <summary>
  ///  Response model for file upload 
  /// </summary>
  public class UploadFileRequest
  {
    /// <summary>
    ///  File name 
    /// </summary>
    public string FileName { get; set; }

    /// <summary>
    ///  File path 
    /// </summary>
    public string FilePath { get; set; }
  }
}

Author: Chasing Time

About the author: A Cheng Xuyuan who loves programming, is good at sharing, likes learning, exploring and trying new things and technologies.


Related articles: