using System.Net.Http.Headers;
依赖注入:
private readonly IHostingEnvironment hostingEnvironment;public HomeController(IHostingEnvironment env){ ?????this.hostingEnvironment = env;}
cshtml 使用 h-ui admin模板(若不需要直接上个 file标签就行):
去掉 file标签中的 accept 限制 可以传各种文件
???????<form asp-controller="Home" role="form" asp-action="ImportExcel" enctype="multipart/form-data" method="post" ?????????????class="form form-horizontal" id="form-add"> ???????????<div class="row cl"> ???????????????<label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>选择Excel <span style="color:red;">xlsx</span> 导入:</label> ???????????????<div class="formControls col-xs-8 col-sm-9"> ???????????????????@*//带文本框*@ ???????????????????<span class="btn-upload form-group"> ???????????????????????<input class="input-text upload-url radius" type="text" name="uploadfile" id="uploadfile" readonly> ???????????????????????<a href="javascript:void();" class="btn btn-primary radius"> ???????????????????????????浏览文件 ???????????????????????</a> ???????????????????????<input type="file" multiple name="fileinput" class="input-file" accept=".xlsx" /> ???????????????????</span> ???????????????</div> ???????????</div> ???????????<div class="row cl"> ???????????????<div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3"> ???????????????????<input class="btn btn-primary radius" type="submit" value=" 提交 "> ???????????????</div> ???????????</div> ???????</form>
Action:
??[HttpPost] ???public async Task<IActionResult> ImportExcel(IFormFile fileinput) ???{ ???????????try ???????????{ ???????????????var filename = ContentDispositionHeaderValue.Parse(fileinput.ContentDisposition).FileName; // 原文件名(包括路径) ???????????????var extName = filename.Substring(filename.LastIndexOf(‘.‘)).Replace("\"", "");// 扩展名 ???????????????string shortfilename = $"{Guid.NewGuid()}{extName}";// 新文件名 ???????????????string fileSavePath = hostingEnvironment.WebRootPath + @"\upload\";//文件临时目录,导入完成后 删除 ???????????????filename = fileSavePath + shortfilename; // 新文件名(包括路径) ???????????????if (!Directory.Exists(fileSavePath)) ???????????????{ ???????????????????Directory.CreateDirectory(fileSavePath); ???????????????} ???????????????using (FileStream fs = System.IO.File.Create(filename)) // 创建新文件 ???????????????{ ???????????????????fileinput.CopyTo(fs);// 复制文件 ???????????????????fs.Flush();// 清空缓冲区数据 ???????????????????//根据 filename 【文件服务器磁盘路径】可对文件进行业务操作 ???????????????} ???????????????//处理完成后,删除上传的文件 ???????????????if (System.IO.File.Exists(filename)) ???????????????{ ???????????????????System.IO.File.Delete(filename); ???????????????} ???????????????return new JsonResult(importResult); ???????????} ???????????catch (Exception ex) ???????????{ ???????????} ???}
.net core 上传excel文件
原文地址:http://blog.51cto.com/11028335/2125988