您好,登錄后才能下訂單哦!
這篇文章主要介紹“ASP.NET Core MVC上傳、導(dǎo)入和導(dǎo)出文件實(shí)例代碼”,在日常操作中,相信很多人在ASP.NET Core MVC上傳、導(dǎo)入和導(dǎo)出文件實(shí)例代碼問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”ASP.NET Core MVC上傳、導(dǎo)入和導(dǎo)出文件實(shí)例代碼”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!
首先我們來看看官網(wǎng)的上傳的例子,再然后進(jìn)行拓展訓(xùn)練,官網(wǎng)的表單是這樣的。
<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); }
后臺(tái)控制器關(guān)于上傳的Action方法進(jìn)行如下定義:
[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 }); }
為了很清楚地上傳文件所在目錄,我們將官網(wǎng)例子進(jìn)行一下改造。
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}個(gè)文件 /{size}字節(jié)上傳成功!"; return View(); }
如上通過注入 private IHostingEnvironment hostingEnv; 來獲取網(wǎng)站根目錄路徑。在前臺(tái)表單中請(qǐng)求action方法用渲染的方式,如下:
<form method="post" enctype="multipart/form-data" asp-controller="Upload" asp-action="UploadFiles"> </form>
當(dāng)然別忘記添加TagHelper:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
成功上傳我們顯示上傳字節(jié)大小,如下:
上傳的文件在網(wǎng)站根目錄下我們能夠看到,如下:
上述我們只是牛刀小試通過表單提交,接下來我們進(jìn)行拓展通過Ajax來提交。我們將表單類型submit修改為button,如下:
<p class="row"> <p class="form-group"> <p class="col-md-10"> <p>使用表單上傳多個(gè)文件</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對(duì)象來獲取文件從而進(jìn)行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("上傳文件出現(xiàn)錯(cuò)誤!"); } }); }); });
此時(shí)后臺(tái)則需要進(jìn)行略微修改,我們不再需要IFormFile接口來獲取文件,通過請(qǐng)求中的表單獲取,如下:
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}個(gè)文件 /{size}字節(jié)上傳成功!"; return View(); }
到這里關(guān)于ASP.NET Core MVC中的上傳就告一段落,還是比較簡(jiǎn)單但是算是比較常見的需求。
項(xiàng)目中需要用到批量導(dǎo)入和導(dǎo)出于是進(jìn)行了一點(diǎn)研究,.net core剛出世時(shí)還未有對(duì)于.net core中Excel的導(dǎo)出,但是見過園中有熱心園友分享并制作了.net core中導(dǎo)出Excel,但是博主發(fā)現(xiàn)在2月19號(hào)有老外已針對(duì).net core的Excel導(dǎo)出和導(dǎo)入目前版本為1.3基于EPPlus,功能和EPPlus差不多,不過是移植到了.net core中,下面我們一起來看看。首先我們下載EPPlus.Core程序包,如下:
我們直接上導(dǎo)出代碼:
[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; }
這里我們進(jìn)行統(tǒng)一封裝下來進(jìn)行導(dǎo)出只需要設(shè)置導(dǎo)出屬性和列表數(shù)據(jù)即可,如下:
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); }
說完導(dǎo)出我們?cè)賮砜磳?dǎo)入,我們來讀取剛剛導(dǎo)入的數(shù)據(jù)返回到頁(yè)面上:
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; } }
此時(shí)我們?cè)賮韺?duì)導(dǎo)入進(jìn)行統(tǒng)一封裝下,如下:
[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); }
到此,關(guān)于“ASP.NET Core MVC上傳、導(dǎo)入和導(dǎo)出文件實(shí)例代碼”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。