- 摘要
本文主要总结,mvc5中前端上传文件的几种方式。
- 后端代码
_hostingEnvironment为IHostingEnvironment 用于获取当前程序物理路径
_hostingEnvironment.WebRootPath 获取路径 “程序根目录/wwwroot”
[HttpPost] public ActionResult UploadFile(List<IFormFile> files) { string name = Guid.NewGuid().ToString("n"); string filePath = _hostingEnvironment.WebRootPath+@"/Files/"; foreach (var formFile in files) { string ext = System.IO.Path.GetExtension(formFile.FileName); System.IO.Directory.CreateDirectory(filePath); if (formFile.Length > 0) { string path = filePath + name + ext; using (var stream = new FileStream(path, FileMode.Create)) { formFile.CopyToAsync(stream); } } } return RedirectToAction("List"); }
- 前端代码
- 传统表单上传文件
<form method="post" enctype="multipart/form-data" action="@Url.Action("UploadFile")"> <div class="form-group"> <div class="col-md-10"> <p>选择文件</p> <input type="file" id="fileImg" name="files" multiple /> </div> </div> <div class="form-group"> <div class="col-md-10"> <input type="submit" value="上 传" /> </div> </div> </form>
2.使用ajax上传文件
1 <form enctype="multipart/form-data"> 2 <div class="form-group"> 3 <div class="col-md-10"> 4 <p>选择文件</p> 5 <input type="file" id="file" name="files" multiple /> 6 </div> 7 </div> 8 <div class="form-group"> 9 <div class="col-md-10"> 10 <input type="button" onclick="ajaxupload()" value="ajax上传" /> 11 <input type="button" onclick="formdataupload()" value="formdata对象上 传" /> 12 <input type="button" onclick="uploadfile()" value="上 传" /> 13 </div> 14 </div> 15 </form> 16 17 <script> 18 function ajaxupload() { 19 var form = new FormData(document.querySelector("form")); 20 $.ajax({ 21 url: "@Url.Action("UploadFile")", 22 type: "POST", 23 data: form, 24 processData: false, // 不处理数据 25 contentType: false // 不设置内容类型 26 }); 27 } 28 </script>
3.FormData对象文件上传
用form表单上传
1 <script> 2 function formdataupload() { 3 4 var formdata = new FormData(document.querySelector("form")); 5 var requst = new XMLHttpRequest(); 6 requst.open("post", "@Url.Action("UploadFile")"); 7 requst.send(formdata); 8 } 9 </script>
不用form表单上传
<script> function uploadFile() { var request = new XMLHttpRequest(); var form = new FormData(); form.append("Id", 23); // 数字23被立即转换成字符串"23" var fileInputElement = $("#fileImg").get(0); // fileInputElement中已经包含了用户所选择的文件 form.append("files", fileInputElement.files[0]); // 这里的files 要与后台List<IFormFile> files 保持一致
request.open("POST", "@Url.Action("UploadFile")"); request.send(form);
} </script>
参考资料
https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects
https://blog.csdn.net/saharalili/article/details/79002568
https://www.cnblogs.com/zhaopei/p/upload.html