Mvc Core Ajax Multipart Form Data Large File Upload
File Upload Tutorial
Uploading a file in an ASP.Cyberspace Zip application is non different than a regular ASP.NET Core application. In this tutorial, nosotros will implement a file upload functionality in ASP.NET Zero. We will also send an boosted field to server while uploading a file.
This tutorial assumes that, you lot already have a valid ASP.Cyberspace Zero license and already created an empty project by following Getting Started document.
You tin implement two different manner of file upload to MVC projects. Ajax based implementation and course based implementation.
Form Based Implementation
- Showtime, create a form named FileUploadViewModel in *.Web.Mvc\Areas\AppAreaName\Models folder. This form volition be used to transfer additional parameters during the upload procedure.
using Microsoft.AspNetCore.Http; public class FileUploadImageViewModel { public string Clarification { get; set; } public IFormFile Epitome { get; set; } }
- Then, create a controller named FileUploadController in *.Web.Mvc\Areas\AppAreaName\Controllers folder.
[Area("AppAreaName")] [AbpMvcAuthorize(AppPermissions.Pages_FileUpload)] public grade FileUploadController : AbpZeroTemplateControllerBase { private readonly IHostEnvironment _env; public FileUploadController(IHostEnvironment env) { _env = env; } public IActionResult Index() { return View(); } [HttpPost] public async Chore<IActionResult> Index(FileUploadViewModel model) { var uniqueFileName = GetUniqueFileName(model.Paradigm.FileName); var dir = Path.Combine(_env.ContentRootPath, "Images"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var filePath = Path.Combine(dir, uniqueFileName); await model.Epitome.CopyToAsync(new FileStream(filePath, FileMode.Create)); return View(); } private cord GetUniqueFileName(string fileName) { fileName = Path.GetFileName(fileName); render Path.GetFileNameWithoutExtension(fileName) + "_" + Guid.NewGuid().ToString().Substring(0, four) + Path.GetExtension(fileName); } individual void SaveImagePathToDb(string description, string filepath) { //todo: description and file path to db } }
- Create a cshtml file named Index.cshtml in *.Web.Mvc\Areas\AppAreaName\Views\FileUpload folder.
<div class="content d-flex flex-column flex-column-fluid"> <abp-page-subheader title="@50("FileUpload")"> </abp-folio-subheader> <div class="@(await GetContainerClass())"> <div grade="card card-custom gutter-b"> <div class="card-trunk"> <form asp-action="Index" enctype="multipart/form-data"> <div grade="form-group"> <label for="Description">@Fifty("Clarification")</label> <input class="class-control" type="text" id="Description" name="Clarification" required> </div> <div grade="class-group"> <characterization for="Epitome">@50("Image")</characterization> <input class="grade-control" type="file" id="Image" name="Prototype" required> </div> <button type="submit" class="btn btn-lite-primary font-weight-assuming close-button">@L("Upload")</button> </grade> </div> </div> </div> </div>
-
Go to *.Web.Mvc\Areas\AppAreaName\Startup\AppAreaNameNavigationProvider.cs and add together a new menu particular.
.AddItem(new MenuItemDefinition( AppAreaNamePageNames.FileUpload, L("FileUpload"), url: "AppAreaName/FileUpload", icon: "flaticon-file-i", permissionDependency: new SimplePermissionDependency(AppPermissions.Pages_FileUpload) ) )
-
So you will have a file upload page every bit seen below.
Afterwards y'all fill the description area, select a file and click to upload, y'all will encounter that it refreshes the page. Not to refresh page you tin can use ajax to upload file.
Ajax Based Implementation
- First, create a class named FileUploadViewModel in *.Spider web.Mvc\Areas\AppAreaName\Models folder. This grade volition exist used to transfer additional parameters during the upload procedure.
public course FileUploadImageViewModel { public cord Description { get; set; } }
- Then, create a controller named FileUploadController in *.Web.Mvc\Areas\AppAreaName\Controllers folder.
[Area("AppAreaName")] [AbpMvcAuthorize(AppPermissions.Pages_FileUpload)] public class FileUploadController : AbpZeroTemplateControllerBase { private readonly IHostEnvironment _env; public FileUploadController(IHostEnvironment env) { _env = env; } public IActionResult Index() { return View(); } [HttpPost] public async Task<string> UploadFile(FileUploadViewModel model) { var image = Request.Form.Files.First(); var uniqueFileName = GetUniqueFileName(image.FileName); var dir = Path.Combine(_env.ContentRootPath, "Images"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var filePath = Path.Combine(dir, uniqueFileName); await image.CopyToAsync(new FileStream(filePath, FileMode.Create)); SaveImagePathToDb(input.Description, filePath); return uniqueFileName; } individual cord GetUniqueFileName(cord fileName) { fileName = Path.GetFileName(fileName); return Path.GetFileNameWithoutExtension(fileName) + "_" + Guid.NewGuid().ToString().Substring(0, four) + Path.GetExtension(fileName); } private void SaveImagePathToDb(string description, string filepath) { //todo: description and file path to db } }
- Create a cshtml file named Index.cshtml in *.Spider web.Mvc\Areas\AppAreaName\Views\FileUpload folder.
@section Scripts{ <script> $('#fileUploadForm').ajaxForm({ success: role (response) { if (response.success) { //you can become result and use it at present. abp.message.success(app.localize("FileSavedSuccessfully", response.issue)); } else { abp.message.error(response.error.bulletin); } } }); </script> } <div class="content d-flex flex-column flex-column-fluid"> <abp-page-subheader title="@L("FileUpload")"> </abp-page-subheader> <div grade="@(await GetContainerClass())"> <div class="card card-custom gutter-b"> <div class="menu-body"> <class id="fileUploadForm" enctype="multipart/form-information" method="post" action="UploadFile"> <div class="form-group"> <label for="Description">@L("Clarification")</label> <input class="class-command" type="text" id="Clarification" proper noun="Clarification" required> </div> <div course="form-group"> <label for="Epitome">@Fifty("Paradigm")</characterization> <input class="form-control" blazon="file" id="Image" proper name="Image" required> </div> <button type="submit" id="btn-upload" class="btn btn-light-chief font-weight-bold close-button">@L("Upload")</button> </form> </div> </div> </div> </div>
- Then yous will have same file upload page.
Later on you fill the description expanse, select a file and click to upload, you lot volition meet that it does not the page. With ajax based file upload you can upload file without refreshing page.
Source: https://docs.aspnetzero.com/en/aspnet-core-mvc/latest/Core-Mvc-File-Upload-Tutorial
0 Response to "Mvc Core Ajax Multipart Form Data Large File Upload"
Post a Comment