Create a project in VS2015.
01.File->New->Project->asp.netcore web application
02.Now we have to Store all the default information like file upload and their path in wwwroot.
wwwroot is new in asp.net core.It is used for all the .css,.js and other file except code base .So the outside there is a code with in .cs file and other asp.net file for seperation of concern.
Now got to appsettings.json and write
#appsettings.json
1 2 3 4 5 6 7 8 9 10 11 |
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } }, "CategoryUploadPath": "uploads/" } |
In Startup.cs file you need to register the dependency in ConfigureServices
#startup
1 2 3 4 5 6 7 |
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddCors(); services.AddSingleton(provider => Configuration);//is important } |
#AjaxFileUpload.cshtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<div> <form asp-action="FileUpload" method="post" enctype="multipart/form-data"> <input type="file" id="files" name="files" multiple /> <input type="submit" id="upload" value="Upload Selected Files" /> </form> </div> <script src="~/lib/jquery/dist/jquery.js"></script> <script> $(document).ready(function () { $("#upload").click(function (evt) { evt.preventDefault(); 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: "/home/UploadFilesAjax", contentType: false, processData: false, data: data, success: function (message) { alert(message); }, error: function () { alert("There was error uploading files!"); } }); }); }); </script> |
#controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
public class HomeController : Controller { private readonly IHostingEnvironment _environment; IConfigurationRoot configuration; public HomeController(IHostingEnvironment environment, IConfigurationRoot _configuration) { _environment = environment; configuration = _configuration; } public IActionResult AjaxFileUpload() { return View(); } [HttpPost] public IActionResult UploadFilesAjax() { long size = 0; var files = Request.Form.Files; var categoryImagepath = configuration["CategoryUploadPath"]; foreach (var file in files) { var filename = ContentDispositionHeaderValue .Parse(file.ContentDisposition) .FileName .Trim('"'); filename = $@"{ _environment.WebRootPath}\{ categoryImagepath}\{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); } public IActionResult FileUpload() { return View(); } [HttpPost] public IActionResult FileUpload(List<IFormFile> files) { IHostingEnvironment environment = new HostingEnvironment(); String fileName = files[0].FileName; var uploads = Path.Combine(_environment.WebRootPath, "uploads"); using (var fileStream = new FileStream(Path.Combine(uploads, fileName), FileMode.Create)) { files[0].CopyTo(fileStream); } return View(); } } |
I have made my default view in SatrtUp.cs
1 2 3 4 5 6 7 8 9 10 |
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { .. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=AjaxFileUpload}/{id?}"); }); } |
#file with other text in ajax
add
1 2 3 |
data.append('Id', Id); data.append('Name', $('#pName').val()); data.append('Description', $('#pDescription').val()); |
and
in controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Guid Id = new Guid(Request.Form["Id"]); String Name = Request.Form["Name"]; String Description = Request.Form["Description"]; String image = String.Empty; if (Request.Form.Files.Count > 0) { IFormFile file = Request.Form.Files[0]; var webRoot = environment.WebRootPath; var categoryImagepath = configuration["CategoryUpload"]; var uploads = Path.Combine(webRoot, categoryImagepath); image = file.FileName; using (var fileStream = new FileStream(Path.Combine(uploads, image), FileMode.Create)) { file.CopyTo(fileStream); } } else { Category category = queryFactory.ResolveQuery<ICategoriesQuery>().Execute().FirstOrDefault(x=>x.Id==Id); image = category.Image; } |