您好,登录后才能下订单哦!
本篇内容主要讲解“asp.net core mvc怎么实现文件上传功能”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“asp.net core mvc怎么实现文件上传功能”吧!
工作用到文件上传的功能,在这个分享下 ~~
Controller:
public class PictureController : Controller { private IHostingEnvironment hostingEnv; public PictureController(IHostingEnvironment env) { this.hostingEnv = env; } // GET: /<controller>/ public IActionResult Index() { return View(); } public IActionResult UploadFiles() { return View(); } [HttpPost] public IActionResult UploadFiles(IList<IFormFile> 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:
<form asp-action="UploadFiles" asp-controller="Picture" method="post" enctype="multipart/form-data"> <input type="file" name="files" multiple /> <input type="submit" value="Upload Selected Files" /> </form>
文件是上传到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
<form method="post" enctype="multipart/form-data"> <input type="file" id="files" name="files" multiple /> <input type="button" id="upload" value="Upload Selected Files" /> </form>
jquery
<script type="text/javascript"> $(document).ready(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: "/Picture/UploadFilesAjax", contentType: false, processData: false, data: data, success: function (message) { alert(message); }, error: function () { alert("There was error uploading files!"); } }); }); }); </script>
到此,相信大家对“asp.net core mvc怎么实现文件上传功能”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。