HttpPostedFileBase getting file extension in Asp.Net MVC

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:

  1. 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" />
}
  1. 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.
  1. 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.

 
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
1 + 8 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice