In ASP.NET MVC, you can use the HttpPostedFileBase
class to handle file uploads. If you want to get the file extension (like ".jpg" or ".png") from an uploaded file using this class, you can follow these simple steps:
- Create an HTML form in your View to allow users to upload files:
@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="Upload" />
}
- In your Controller, create an action method that will handle the file upload and get the file extension:
using System.IO;
using System.Web.Mvc;
public class FileController : Controller
{
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
// Get the file extension from the uploaded file's name
string fileExtension = Path.GetExtension(file.FileName);
// Do something with the file extension, for example, display it in the view
ViewBag.FileExtension = fileExtension;
}
return View();
}
}
In the above code:
- The
HttpPostedFileBase
parameter named file
in the Upload
action method represents the uploaded file.
- We check if the file is not null and has content.
- We use
Path.GetExtension
to get the file extension from the file.FileName
.
- You can then use or display the
fileExtension
as needed, for example, by passing it to the view.
- Create a View to display the file extension or perform further actions:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>File Upload Result</title>
</head>
<body>
@if (ViewBag.FileExtension != null)
{
<p>Uploaded file extension: @ViewBag.FileExtension</p>
}
else
{
<p>No file uploaded.</p>
}
</body>
</html>
Now, when a user uploads a file using the form, the controller will get the file extension and display it on the result page.