How much does ASP. NET Core MVC upload, import, export know

Source: Internet
Author: User
Tags rowcount


Objective



Says has become a night owl, this section we talk about the upload in ASP. NET Core MVC, these two days in the study of bulk Import function, this section by simple to engage in import, export, and other bloggers get it properly and then to share with you.






. NET Core MVC uploads



First, we take a look at the official website upload example, and then to expand training, the official website of the form is such.


<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>


The file received for upload in ASP. NET Core MVC needs to be received by Iformfile, which 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 about the upload action method is defined 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 very clearly upload the directory of the file, we have a network example of the change.


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 ('"');
           fileName = hostingEnv.WebRootPath + $ @ "\ {fileName}";
           size + = file.Length;
           using (FileStream fs = System.IO.File.Create (fileName))
           {
              file.CopyTo (fs);
               fs.Flush ();
           }
       }
       ViewBag.Message = $ "{files.Count} files / {size} bytes uploaded successfully!";
       return View ();
   }


As above by injecting private ihostingenvironment hostingenv; To get the site root directory path. In the foreground form, request the action method in the way it is rendered, 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


Successfully uploaded we display the upload byte size as follows:






The uploaded file at the root of the Web site we can see, as follows:






The above we just kind through the form submission, next we expand through Ajax to submit. We modified the form type submit to a button, as follows:


<p class = "row">
     <p class = "form-group">
          <p class = "col-md-10">
                     <p> Upload multiple files using a form </ 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 = "upload" />
           </ p>
      </ p>
  </ p>


We use the Formdata object to get the file for Ajax submissions, 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 ("Error uploading file!");
               }
            });
        });
    });


At this point the background needs to be slightly modified, we no longer need the Iformfile interface to get the file, through the request of the form to obtain, 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 ('"');
          fileName = hostingEnv.WebRootPath + $ @ "\ {fileName}";
          size + = file.Length;
          using (FileStream fs = System.IO.File.Create (fileName))
          {
              file.CopyTo (fs);
              fs.Flush ();
          }
      }
      ViewBag.Message = $ "{files.Count} files / {size} bytes uploaded successfully!";
      return View ();
  }


It is still a simple but more common requirement to have an upload in ASP. NET Core mvc.



Import, export Excel



Bulk import and export required in the project a little research has been done, and. NET core was not exported to excel in. NET core at the time of its birth, but I have seen a warm-hearted friend in the garden to share and make a. NET core export Excel, But the blogger found out that on February 19 a foreigner had exported and imported Excel for. NET core, and the current version is 1.3 based on Epplus, features and Epplus almost, but ported to. NET core, let's take a look. First we download the Epplus.core package, as follows:






We export the code directly:


  [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 do a unified package to export 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);
 }








Finish exporting and we'll look at the import, we'll read the data just imported back 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;
   }
}





Now let's do this in a uniform package of imports, 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);
  }





Introduction is probably finished, I say the real difficulty is not to use Epplus import and export, the difficulty lies in the bulk import, batch import data format after the test, if given an import template, and then import the bulk data how to ensure that the user gave the data format is completely correct and the data does not duplicate the checksum , these two days are basically completed batch import, roughly divided into: data must be filled in the check, data format verification, database existence data validation, data import partial import failed to return the format of the user experience. When using Npoi, Epplus to import and export such functionality is simple, but if you encounter a different scenario how to make the user experience better use this is a problem, if the data import failed how do we prompt the user? And if there's a drop-down box and merged cell data in Excel, how do we get to this is another problem, maybe a lot of resumes are written on the use of Npoi and Epplus import and export, in fact, nothing to watch, they are just a tool, How to use tools to apply to complex scenes and for example that is a high-level thing.



Summarize



This section gives you a little introduction to download, import, and export in. NET core, and if possible follow up on the advanced knowledge of epplus, such as getting merged column data and getting pictures, etc., we'll see you next, oh, about SQL The server has time to update periodically, see U.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.