asp.net core mvc实现文件上传实例
工作用到文件上传的功能,在这个分享下~~
Controller:
publicclassPictureController:Controller { privateIHostingEnvironmenthostingEnv; publicPictureController(IHostingEnvironmentenv) { this.hostingEnv=env; } //GET:/<controller>/ publicIActionResultIndex() { returnView(); } publicIActionResultUploadFiles() { returnView(); } [HttpPost] publicIActionResultUploadFiles(IList<IFormFile>files) { longsize=0; foreach(varfileinfiles) { varfilename=ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); //这个hostingEnv.WebRootPath就是要存的地址可以改下 filename=hostingEnv.WebRootPath+$@"\{filename}"; size+=file.Length; using(FileStreamfs=System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } } ViewBag.Message=$"{files.Count}file(s)/{size}bytesuploadedsuccessfully!"; returnView(); } }
view:
<formasp-action="UploadFiles" asp-controller="Picture" method="post" enctype="multipart/form-data"> <inputtype="file"name="files"multiple/> <inputtype="submit"value="UploadSelectedFiles"/> </form>
文件是上传到wwwroot目录文件下的,这我也看不太懂还在学习,欢迎大家交流~~
----------------------------------------------------------------------------------------------------------
下面是jqueryajax方式上传的
post方式的action的z参数没用因为只有一个post方式的会404错误所以又加了一个get的action
Controller:
publicIActionResultUploadFilesAjax() { returnView(); } [HttpPost] publicIActionResultUploadFilesAjax(stringz) { longsize=0; varfiles=Request.Form.Files; foreach(varfileinfiles) { varfilename=ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); filename=@"C:\Users\lg.HL\Desktop"+$@"\{filename}"; size+=file.Length; using(FileStreamfs=System.IO.File.Create(filename)) { file.CopyTo(fs); fs.Flush(); } } stringmessage=$"{files.Count}file(s)/{size}bytesuploadedsuccessfully!"; returnJson(message); }
view
<formmethod="post"enctype="multipart/form-data"> <inputtype="file"id="files" name="files"multiple/> <inputtype="button" id="upload" value="UploadSelectedFiles"/> </form>
jquery
<scripttype="text/javascript"> $(document).ready(function(){ $("#upload").click(function(evt){ varfileUpload=$("#files").get(0); varfiles=fileUpload.files; vardata=newFormData(); for(vari=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("Therewaserroruploadingfiles!"); } }); }); }); </script>
欢迎大家交流~以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。