In this article i will show you how you can upload a file in an user created folder which is not present in wwwroot folder in asp.net core 6/ mvc application using c#.net. Now for this article first we will create a new folder which is not present in your wwwroot folder. This uploaded file will not be accessible on http. It will be same as we upload file in App_Data folder.
Other Related Articles: Upload Multiple File To wwwroot Folder in ASP.NET Core Using C#.Net, Asp.net Core 6 Multiple File Upload, How To Upload Multiple File Asp.net core 6, Upload File To wwwroot Folder in ASP.NET Core Using C#.Net, How To Upload File Asp.net core 6.
Now for this article first we will create new asp.net core 6 / mvc project and add a folder in your project.
Now we will add controller and create a view. In this view add the below code.
@{ ViewData["Title"] = "Home Page"; } @using
(Html.BeginForm("Index", "Home",
FormMethod.Post, new { @enctype = "multipart/form-data" })) { <span style="font-weight:bold;">Upload File</span> <br /> <span style="color:red;">@ViewBag.Message</span> <br /> <input type="file" name="formFile" /> <input type="submit" value="Submit" /> } |
In above code just check the highlighted part of the code. In this the name of the file control. You need the make sure that the parameter which you pass on postback will be same as the control name. Second thing the enctyp must be added in the form tag.
Now in our controller we will write code to upload the file. For this we will prepare a post method and in this post method we will add the below code.
[HttpPost] public
IActionResult Index(IFormFile formFile) { try { string fileName = Path.GetFileName(formFile.FileName); string uploadpath =
Path.Combine(Directory.GetCurrentDirectory(), "UserFiles", fileName); var stream = new FileStream(uploadpath,
FileMode.Create); formFile.CopyToAsync(stream); ViewBag.Message = "File uploaded
successfully."; } catch { ViewBag.Message = "Error while uploading the
files."; } return View(); } |
0 comments:
Please let me know your view