这篇文章主要介绍“ASP.NET Core MVC上传、导入和导出文件实例代码”,在日常操作中,相信很多人在ASP.NET Core MVC上传、导入和导出文件实例代码问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”ASP.NET Core MVC上传、导入和导出文件实例代码”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
创新互联专注于新丰网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供新丰营销型网站建设,新丰网站制作、新丰网页设计、新丰网站官网定制、重庆小程序开发服务,打造新丰网络公司原创品牌,更为您提供新丰网站排名全网营销落地服务。
.NET Core MVC上传
首先我们来看看官网的上传的例子,再然后进行拓展训练,官网的表单是这样的。
在ASP.NET Core MVC中接收上传的文件需要用 IFormFile 来接收,该接口定义如下:
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); }
后台控制器关于上传的Action方法进行如下定义:
[HttpPost("UploadFiles")] public async TaskPost(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 }); }
为了很清楚地上传文件所在目录,我们将官网例子进行一下改造。
public IActionResult UploadFiles(Listfiles) { 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(); }
如上通过注入 private IHostingEnvironment hostingEnv; 来获取网站根目录路径。在前台表单中请求action方法用渲染的方式,如下:
当然别忘记添加TagHelper:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
成功上传我们显示上传字节大小,如下:
上传的文件在网站根目录下我们能够看到,如下:
上述我们只是牛刀小试通过表单提交,接下来我们进行拓展通过Ajax来提交。我们将表单类型submit修改为button,如下:
使用表单上传多个文件
@ViewBag.Message
我们通过FormData对象来获取文件从而进行Ajax提交,如下:
$(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; }
这里我们进行统一封装下来进行导出只需要设置导出属性和列表数据即可,如下:
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); }
说完导出我们再来看导入,我们来读取刚刚导入的数据返回到页面上:
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; } }
此时我们再来对导入进行统一封装下,如下:
[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); }
到此,关于“ASP.NET Core MVC上传、导入和导出文件实例代码”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!
本文题目:ASP.NETCoreMVC上传、导入和导出文件实例代码
路径分享:http://scgulin.cn/article/gdhgig.html