您现在的位置是:网站首页> 编程资料编程资料

asp.net core mvc实现文件上传实例_实用技巧_

2023-05-24 358人已围观

简介 asp.net core mvc实现文件上传实例_实用技巧_

工作用到文件上传的功能,在这个分享下 ~~

Controller:        

 public class PictureController : Controller { private IHostingEnvironment hostingEnv; public PictureController(IHostingEnvironment env) { this.hostingEnv = env; } // GET: // public IActionResult Index() { return View(); } public IActionResult UploadFiles() { return View(); } [HttpPost] public IActionResult UploadFiles(IList files) { long size = 0; foreach (var file in files) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); //这个hostingEnv.WebRootPath就是要存的地址可以改下 filename = hostingEnv.WebRootPath + $@"\{filename}"; size += file.Length; using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } } ViewBag.Message = $"{files.Count} file(s) /{ size}bytes uploaded successfully!"; return View(); } } 

view:

文件是上传到wwwroot目录文件下的,这我也看不太懂还在学习,欢迎大家交流~~

----------------------------------------------------------------------------------------------------------

下面是jquery ajax方式上传的

post方式的action的z参数没用 因为只有一个post方式的会404错误所以又加了一个get的action

Controller: 

 public IActionResult UploadFilesAjax() { return View(); } [HttpPost] public IActionResult UploadFilesAjax(string z) { long size = 0; var files = Request.Form.Files; foreach (var file in files) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); filename = @"C:\Users\lg.HL\Desktop" + $@"\{filename}"; size += file.Length; using (FileStream fs = System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } } string message = $"{files.Count} file(s) / { size}bytes uploaded successfully!"; return Json(message); }

view

jquery

欢迎大家交流~ 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

-六神源码网