这篇文章主要介绍“ASP.NET Core MVC上传、导入和导出文件实例代码”,在日常操作中,相信很多人在ASP.NET Core MVC上传、导入和导出文件实例代码问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”ASP.NET Core MVC上传、导入和导出文件实例代码”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
首先我们来看看官网的上传的例子,再然后进行拓展训练,官网的表单是这样的。
<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>
在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 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 }); }
为了很清楚地上传文件所在目录,我们将官网例子进行一下改造。
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(); }
如上通过注入 private IHostingEnvironment hostingEnv; 来获取网站根目录路径。在前台表单中请求action方法用渲染的方式,如下:
<form method="post" enctype="multipart/form-data" asp-controller="Upload" asp-action="UploadFiles"> </form>
当然别忘记添加TagHelper:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
成功上传我们显示上传字节大小,如下:
上传的文件在网站根目录下我们能够看到,如下:
上述我们只是牛刀小试通过表单提交,接下来我们进行拓展通过Ajax来提交。我们将表单类型submit修改为button,如下:
<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>
我们通过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中的上传就告一段落,还是比较简单但是算是比较常见的需求。
项目中需要用到批量导入和导出于是进行了一点研究,.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<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); }
说完导出我们再来看导入,我们来读取刚刚导入的数据返回到页面上:
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上传、导入和导出文件实例代码”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。