search
HomeBackend DevelopmentC#.Net TutorialHow much do you know about uploading, importing and exporting ASP.NET Core MVC?

Preface

I have become a night owl, so in this section we will talk about uploading in ASP.NET Core MVC. I have been studying the batch import function in the past two days. In this section, I will briefly talk about import and export. I will come back to you when the blogger has it right. and share.

.NET Core MVC upload

First, let’s take a look at the upload example on the official website, and then conduct expansion training. The form on the official website looks like this.

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

To receive uploaded files in ASP.NET Core MVC, you need to use IFormFile to receive them. The interface is defined as follows:

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);
}

The background controller defines the uploaded Action method as follows:

 [HttpPost("UploadFiles")]
  public async Task<IActionResult> Post(List<IFormFile> files)
  {
     long size = files.Sum(f => f.Length);

     // full path to file in temp location
     var filePath = Path.GetTempFileName();

     foreach (var formFile in files)
     {
       if (formFile.Length > 0)
       {
           using (var stream = new FileStream(filePath, FileMode.Create))
           {
              await formFile.CopyToAsync(stream);
           }
       }
     }
     return Ok(new { count = files.Count, size, filePath });
 }

In order to clearly indicate the directory where the uploaded file is located, we will modify the official website example.

  public IActionResult UploadFiles(List<IFormFile> files)
  {
      long size = 0;
      foreach (var file in files)
      {
         //var fileName = file.FileName;
         var fileName = ContentDispositionHeaderValue
                         .Parse(file.ContentDisposition)
                         .FileName
                         .Trim(&#39;"&#39;);
          fileName = hostingEnv.WebRootPath + $@"\{fileName}";
          size += file.Length;
          using (FileStream fs = System.IO.File.Create(fileName))
          {
             file.CopyTo(fs);
              fs.Flush();
          }
      }
      ViewBag.Message = $"{files.Count}个文件 /{size}字节上传成功!";
      return View();
  }

As above, obtain the website root directory path by injecting private IHostingEnvironment hostingEnv;. Request the action method in the front form by rendering, as follows:

<form method="post" enctype="multipart/form-data" asp-controller="Upload" asp-action="UploadFiles">
</form>

Of course don’t forget to add TagHelper:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

After a successful upload, we display the uploaded byte size, as follows:

We can see the uploaded files in the root directory of the website, as follows:

The above is just a small test of submitting through the form. Next, we will expand to submit through Ajax. We change the form type submit to button, as follows:

 <p class="row">
    <p class="form-group">
         <p class="col-md-10">
                    <p>使用表单上传多个文件</p>
                    <input type="file" id="files" name="files" multiple />
                    @ViewBag.Message
         </p>
     </p>
 </p>

 <p class="row">
     <p class="form-group">
          <p class="col-md-10">
                 <input type="button" id="upload" class="btn btn-success" style="cursor:pointer;width:100px;" value="上传" />
          </p>
     </p> 
 </p>

We use the FormData object to obtain the file for Ajax submission, as follows:

  $(function () {
      $("#upload").click(function (evt) {
           var fileUpload = $("#files").get(0);
           var files = fileUpload.files;
           var data = new FormData();
           for (var i = 0; i < files.length ; i++) {
               data.append(files[i].name, files[i]);
           }
           $.ajax({
              type: "POST",
              url: "/Upload/UploadFiles",
              contentType: false,
              processData: false,
              data: data,
              success: function (message) {
                  alert(message);
              },
              error: function () {
                  alert("上传文件出现错误!");
              }
           });
       });
   });

At this time, the background needs to be slightly modified. We no longer need the IFormFile interface to obtain the file, but obtain it through the form in the request, as follows:

 public IActionResult UploadFiles()
 {
    long size = 0;
    var files = Request.Form.Files;
    foreach (var file in files)
    {
         //var fileName = file.FileName;
         var fileName = ContentDispositionHeaderValue
                        .Parse(file.ContentDisposition)
                        .FileName
                        .Trim(&#39;"&#39;);
         fileName = hostingEnv.WebRootPath + $@"\{fileName}";
         size += file.Length;
         using (FileStream fs = System.IO.File.Create(fileName))
         {
             file.CopyTo(fs);
             fs.Flush();
         }
     }
     ViewBag.Message = $"{files.Count}个文件 /{size}字节上传成功!";
     return View();
 }

At this point, the upload in ASP.NET Core MVC comes to an end. It is still relatively simple but a relatively common requirement.

Import and export Excel

The project needed to use batch import and export, so I did some research. When .net core was first born, there was no export for Excel in .net core. However, I saw some enthusiastic gardeners in the garden sharing and making it. Export Excel, but the blogger discovered that on February 19th, a foreigner had exported and imported Excel for .net core. The current version is 1.3 based on EPPlus. The functions are similar to EPPlus, but it has been transplanted to .net core. Let’s take a look. look. First we download the EPPlus.Core package, as follows:

We directly export the code:

  [HttpGet]
  [Route("Export")]
  public string Export()
  {
      string sWebRootFolder = _hostingEnvironment.WebRootPath;
      string sFileName = @"Jeffcky.xlsx";
      string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
      FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
      if (file.Exists)
      {
          file.Delete();
          file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
      }
      using (ExcelPackage package = new ExcelPackage(file))
      {
          // add a new worksheet
          ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Jeffcky");
                
          //sheet header
          worksheet.Cells[1, 1].Value = "ID";
          worksheet.Cells[1, 2].Value = "Name";
          worksheet.Cells[1, 3].Value = "Age";

          //Add values
          worksheet.Cells["A2"].Value = 1000;
          worksheet.Cells["B2"].Value = "Jeffcky1";
          worksheet.Cells["C2"].Value = 18;

          worksheet.Cells["A3"].Value = 1001;
          worksheet.Cells["B3"].Value = "Jeffcky2";
          worksheet.Cells["C3"].Value = 19;


          package.Save(); //Save the workbook.
      }
      return URL;

  }

Here we encapsulate it uniformly for export and only need to set the export properties and list data, as follows:

public IActionResult Export()
{
    var properties = new PropertyByName<Person>[]
    {
         new PropertyByName<Person>("Id",d=>d.Id),
         new PropertyByName<Person>("Name",d=>d.Name),
         new PropertyByName<Person>("Age",d=>d.Age)
     };

     var list = new List<Person>()
     {
         new Person() {Id=1,Name="Jeffcky1",Age=18 },
         new Person() {Id=2,Name="Jeffcky2",Age=19 },
         new Person() {Id=3,Name="Jeffcky3",Age=20 },
         new Person() {Id=4,Name="Jeffcky4",Age=21 },
         new Person() {Id=5,Name="Jeffcky5",Age=22 }
     };
     var bytes = _ExportManager.ExportToXlsx<Person>(properties, list);
     return new FileContentResult(bytes, MimeTypes.TextXlsx);
 }

After talking about export, let’s look at import. Let’s read the data we just imported and return it to the page:

 public string Import()
 {
    string sWebRootFolder = _hostingEnvironment.WebRootPath;
    string sFileName = @"Jeffcky.xlsx";
    FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
    try
    {
        using (ExcelPackage package = new ExcelPackage(file))
        {
            StringBuilder sb = new StringBuilder();
            ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
            int rowCount = worksheet.Dimension.Rows;
            int ColCount = worksheet.Dimension.Columns;
            bool bHeaderRow = true;
            for (int row = 1; row <= rowCount; row++)
            {
                for (int col = 1; col <= ColCount; col++)
                {
                    if (bHeaderRow)
                    {
                         sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
                    }
                    else
                    {
                         sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
                    }
                 }
                 sb.Append(Environment.NewLine);
            }
            return sb.ToString();
       }
   }
   catch (Exception ex)
   {
       return "Some error occured while importing." + ex.Message;
   }
}

At this time, we will uniformly encapsulate the import, as follows:

 [HttpGet]
 [Route("Import")]
 public void Import()
 {
    string sWebRootFolder = _hostingEnvironment.WebRootPath;
    string sFileName = @"Jeffcky.xlsx";
    FileStream fs = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Open, FileAccess.Read, FileShare.Read);
    var list = _ImportManager.ImportPersonFromXlsx(fs);
  }

The introduction of import is probably over. I would say that the real difficulty is not to use EPPlus to import and export. The difficulty lies in batch import. After batch import, the data format is checked. If an import template is given and then the batch data is imported, how to ensure that The data format provided by the user is completely correct and the data has not been repeatedly verified. In the past two days, the batch import has basically been completed, which can be roughly divided into: verification of required data items, verification of data format, and whether the database exists. Verification of data, user experience of the return format if the data import part fails to import. When using NPOI and EPPlus to import and export such functions, it couldn't be easier. However, if different scenarios are encountered, how to make the user experience better is a problem. If the data import fails, how do we prompt the user? If there are drop-down boxes and merged cell data in Excel, how do we get it? This is another question. Many resumes may say that they will use NPOI and EPPlus to import and export. In fact, it is not interesting. The two are just a tool. , how to use tools to apply to complex scenarios and give examples is what is considered advanced.

Summarize

In this section, we briefly introduce downloading, importing and exporting in .net core. If possible, we will provide advanced knowledge about EPPlus later, such as obtaining merged column data and obtaining pictures as mentioned above. We will follow the next section. Goodbye, oh, SQL Server will be updated regularly when there is time, see u.

The above is the detailed content of How much do you know about uploading, importing and exporting ASP.NET Core MVC?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C# .NET Interview Questions & Answers: Level Up Your ExpertiseC# .NET Interview Questions & Answers: Level Up Your ExpertiseApr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

Building Microservices with C# .NET: A Practical Guide for ArchitectsBuilding Microservices with C# .NET: A Practical Guide for ArchitectsApr 06, 2025 am 12:08 AM

C#.NET is a popular choice for building microservices because of its strong ecosystem and rich support. 1) Create RESTfulAPI using ASP.NETCore to process order creation and query. 2) Use gRPC to achieve efficient communication between microservices, define and implement order services. 3) Simplify deployment and management through Docker containerized microservices.

C# .NET Security Best Practices: Preventing Common VulnerabilitiesC# .NET Security Best Practices: Preventing Common VulnerabilitiesApr 05, 2025 am 12:01 AM

Security best practices for C# and .NET include input verification, output encoding, exception handling, as well as authentication and authorization. 1) Use regular expressions or built-in methods to verify input to prevent malicious data from entering the system. 2) Output encoding to prevent XSS attacks, use the HttpUtility.HtmlEncode method. 3) Exception handling avoids information leakage, records errors but does not return detailed information to the user. 4) Use ASP.NETIdentity and Claims-based authorization to protect applications from unauthorized access.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use