asp.net core mvc实现文件上传实例
程序员文章站
2022-04-29 09:32:42
工作用到文件上传的功能,在这个分享下 ~~
controller: ...
工作用到文件上传的功能,在这个分享下 ~~
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>
欢迎大家交流~ 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。