Home >Backend Development >C#.Net Tutorial >Detailed explanation of upload, import and export of ASP.NET Core MVC
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.
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('"'); 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('"'); 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.
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.
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 Detailed explanation of upload, import and export of ASP.NET Core MVC. For more information, please follow other related articles on the PHP Chinese website!