1.前言
文件导入导出是简单且常用的功能,以下示例实现了文件上传与下载的几种方法,如有不妥的地方,欢迎指正。小白一枚,在往目标前进。
2.1.文件上传 -- 纯文件
1 <form action="/Home/Index" method ="post" enctype="multipart/form-data" > 2 <input type="file" multiple/> 3 <input id="upload" type="submit" /> 4 </form>
1 [HttpPost] 2 public IActionResult Index(List<IFormFile> files) 3 { 4 5 foreach (var file in files) 6 { 7 //获取文件名 8 var fileName = file.FileName; 9 //保存在wwwroot文件夹下 10 fileName = hostingEnv.WebRootPath + $"\{fileName}";12 using (FileStream fs = System.IO.File.Create(fileName)) 13 { 14 file.CopyTo(fs); 15 fs.Flush(); 16 } 17 } 18 return View(); 19 }
2.2.文件上传 -- 多类型内容上传
对于这种不只有文件的表单,可以采用模型绑定的方式。
<form action="/Home/Index" method ="post" enctype="multipart/form-data" >
<input type="file" multiple/>
<input type="text" name="Name"/>
<input id="upload" type="submit" />
</form>
/// <summary> /// 表单上传文件 /// </summary> /// <param name="files"></param> /// <returns></returns> [HttpPost] public IActionResult Index(FormObject obj) { foreach (var file in obj.Files) { //获取文件名 var fileName = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); fileName = hostingEnv.WebRootPath + $"\{fileName}"; using (FileStream fs = System.IO.File.Create(fileName)) { file.CopyTo(fs); fs.Flush(); } } return View(); }
//模型类 public class FormObject { public List<IFormFile> Files{ get; set; } public string Name { get; set; } }
2.3.文件上传 -- Ajax上传
<input type="text" name="Name" value="123"/> <input type="file" id="fileUpload" name="fileUpload" multiple/> <input id="upload" type="button" value="ajax 提交"/>
<script type="text/javascript"> $(function () { $("#upload").click(function (evt) { ///取选择的文件加入FormData中 var fileUpload = $("#fileUpload").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]); } // data.append("Name", $('input[name="Name"]').val()) $.ajax({ type: "POST", url: "http://192.168.0.175:8095/api/Organization", contentType: false, processData: false, data: data, success: function (message) { alert(message); }, error: function () { alert("上传文件出现错误!"); } }); }); }); </script>
/// <summary> /// 通过ajax上传 /// </summary> /// <returns></returns> public IActionResult UploadFiles() {var files = Request.Form.Files; var value =Request.Form.First(c => c.Key == "Name").Value;//获得表单文本项 foreach (var file in files) { var fileName = file.FileName; fileName = hostingEnv.WebRootPath + $@"{fileName}";using (FileStream fs = System.IO.File.Create(fileName)) { file.CopyTo(fs); fs.Flush(); } } return RedirectToAction("/Export", new { Title ="1",Name = 123}); }
3.3.文件下载
1 [HttpGet] 2 public IActionResult ExportText() 3 { 4 5 string sFileName = $@"qmhuangtext{DateTime.Now.ToString("yyyyMMddHHmmss")}.txt"; 6 FileStream fs =new FileStream(sFileName,FileMode.OpenOrCreate); 7 StreamWriter sw = new StreamWriter(fs); 8 sw.WriteLine("Hello world"); 9 sw.Flush(); 10 sw.Close(); 11 fs.Close(); 12 return File(new FileStream(sFileName, FileMode.Open), "application/octet-stream", $"导出测试{DateTime.Now.ToString("yyyyMMddHHmmss")}.txt"); 13 }