After this we will add a controller file and add a HttpGet method as Index(). This HttpGet method act as a page load for your asp.net core mvc application.
[HttpGet]
public IActionResult Index()
{
return View();
}
In above code I have define a method with return type as IActionResult with HttpGet method. Now lets create a view. In a view we will add our all Html code base. @{
ViewData["Title"] = "Home Page";
<script src="~/lib/jquery/dist/jquery.min.js"></script>
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
<div style="color:red" id="divmessage">@ViewBag.Message</div>
<div style="font-weight:bold;">Select File:</div>
<div>
<input type="file" class="form-control" name="file" id="filecontrol" />
</div>
<br />
<div>
<input type="submit" value="Upload File" onclick="javascript: return ValidteFileSize();" />
</div>
}
<script>
var ValidteFileSize = function () {
const fileExtentions = ["png", "gif", "jpg","jpeg","bmp"];
var fext = $("#filecontrol").val().split('.').pop();
if (!fileExtentions.includes(fext))
$("#divmessage").html("Image file type like .jpeg, .png, .bmp etc is only allowed to upload.");
return false;
}
return true;
}
</script>
Here in above code, I have added the jQuery reference. Here I have added in the view but you need to add in the Layout page. to keep it common. You can download the jQuery library from given url.
Dopwnload jQuery https://code.jquery.com/jquery-3.7.1.js
In above code after adding the jQuery reference check the form tag.
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
In next line I have taken the div control to display the message. Here I have taken the @ViewBag.Message to display the message send from controller end. In next line I have taken the input control of file type. to upload the browse the file. Here I have taken the file control name as name='file'. This name of the file must be same as the parameter passed to the HttpPost method. In next line i have taken the Submit to submit the file to upload.
Please refer the below jQuery code.
<script>
var ValidteFileSize = function () {
const fileExtentions = ["png", "gif", "jpg","jpeg","bmp"];
var fext = $("#filecontrol").val().split('.').pop();
if (!fileExtentions.includes(fext))
$("#divmessage").html("Image file type like .jpeg, .png, .bmp etc is only allowed to upload.");
return false;
}
return true;
}
</script>
In above code I have taken an array with image file extensions. If you want to add more or want to reduce the exitron you can do it in the array list. After defining the array of file extensions. I have extracted the file extension by using jQuery. In next line I have validated the file extension, If the file extension is png, gif, jpg, jpeg or bmp on that case return true otherwise return false with a user-friendly message to user. Here $("#filecontrol").val().split('.').pop() code is used for getting the selected file extension. On click of submit button I have called the file extension validation method which is as follows "onclick="javascript: return ValidteFileSize();".
Now add the below code for HttpPost method.
[HttpPost]
public IActionResult Index(IFormFile file)
{
if (file != null)
{
try
{
string parentPath = @"wwwroot\Demofiles\";
string uploadfilepath = Path.Combine(Directory.GetCurrentDirectory(), parentPath, file.FileName);
var filestream = new FileStream(uploadfilepath, FileMode.Create);
file.CopyToAsync(filestream);
string dbSaveUploadPath = string.Format("{0}{1}", @"\Demofiles\", file.FileName);
ViewBag.Message = "File uploaded successfully.";
}
catch (Exception ex)
{
ViewBag.Message = ex.Message;
}
}
else
{
ViewBag.Message = "Please select file to upload.";
}
return View();
}
In above code you can check the passed parameter name. It is same as the file upload control name. after that validation for file is selected or not is applied. After that I have prepared the path to upload the file. FileStream(path, FileMode.Create) is used to create the filestream. After that I have used CopyToAsync to make the copy of the file in the specified file. In View bag I have added to message to display at user end. Now we have done run the code and select a pdf file.Now select a non-image file. Let's select a pdf or text file.
Now click on button to upload the file, we will get the error.
Now let's select the png, gif, jpg, jpeg or bmp file and click on upload button.
Here you can see the file we have uploaded, we are getting at controller end. Here one you must notice that the passed parameter name and the file upload input control name is same. If you don't keep both things same, you will not be able to get the uploaded file detail at controller end.
Now click on upload button to check the output.
Now let's check the upload folder.
If you like the article and it is helpful to you, please let me know in comment.