Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

ASP.NET Core MVC upload, import and export file instance codes

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "ASP.NET Core MVC upload, import and export file instance code". In the daily operation, I believe that many people have doubts about ASP.NET Core MVC upload, import and export file instance code. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "ASP.NET Core MVC upload, import and export file instance code". Next, please follow the editor to study!

.net Core MVC upload

First of all, let's take a look at the example of uploading on the official website, and then carry out expansion training. The form on the official website is like this.

Upload one or more files using this form:

You need to use IFormFile to receive uploaded files in ASP.NET Core MVC. This API 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 backend controller defines the Action method for upload as follows:

[HttpPost ("UploadFiles")] public async Task Post (List 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 upload the directory where the files are located, we will modify the example of the official website.

Public IActionResult UploadFiles (List 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 ();}

Get the root path of the site by injecting private IHostingEnvironment hostingEnv; as above. Request the action method in the foreground form to render, as follows:

Of course, don't forget to add TagHelper:

@ addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

For a successful upload, the upload byte size is displayed as follows:

The uploaded files can be seen in the root directory of the website, as follows:

The above we just try to submit through the form, and then we will expand to submit through Ajax. We changed the form type submit to button, as follows:

Upload multiple files using a form

@ ViewBag.Message

We use the FormData object to get 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("上传文件出现错误!"); } }); }); });   此时后台则需要进行略微修改,我们不再需要IFormFile接口来获取文件,通过请求中的表单获取,如下: 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(); }   到这里关于ASP.NET Core MVC中的上传就告一段落,还是比较简单但是算是比较常见的需求。  导入、导出Excel   项目中需要用到批量导入和导出于是进行了一点研究,.net core刚出世时还未有对于.net core中Excel的导出,但是见过园中有热心园友分享并制作了.net core中导出Excel,但是博主发现在2月19号有老外已针对.net core的Excel导出和导入目前版本为1.3基于EPPlus,功能和EPPlus差不多,不过是移植到了.net core中,下面我们一起来看看。首先我们下载EPPlus.Core程序包,如下:   我们直接上导出代码: [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 only need to set the export attributes and list data for export under a unified package, as follows:

Public IActionResult Export () {var properties = new PropertyByName [] {new PropertyByName ("Id", d = > d.Id), new PropertyByName ("Name", d = > d.Name), new PropertyByName ("Age", d = > d.Age)} Var list = new List () {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 (properties, list) Return new FileContentResult (bytes, MimeTypes.TextXlsx);}

After we finish exporting, let's look at the import. Let's read the data 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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report