本君已成夜貓子,本節我們來講講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>
@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>
$(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("上传文件出现错误!"); } }); }); });
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(); }
# 我們直接上匯出程式碼:
[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); }
本節我們稍微介紹了.net core中的下載、導入和導出,如果有可能的話後續會給出關於EPPlus中高級的知識,比如如上提出的獲取合併列數據還有獲取圖片等等,我們下節再會,哦,關於SQL Server有時間會定期進行更新,see u。
以上是ASP.NET Core MVC上傳、匯入、匯出詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!