您好,登錄后才能下訂單哦!
這篇文章主要介紹asp.net如何實現文件上傳,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
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如何實現文件上傳”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。