Skip to content

Instantly share code, notes, and snippets.

@ankitkanojia
Last active January 2, 2024 23:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ankitkanojia/95b3998a3e7f1a1b93f8da048f52c38f to your computer and use it in GitHub Desktop.
Save ankitkanojia/95b3998a3e7f1a1b93f8da048f52c38f to your computer and use it in GitHub Desktop.
Upload/Save media file using HttpPostedFileBase class in C# MVC
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace YourProjectNameSpace.Helpers
{
public static class Utilities
{
public static string SaveFile(HttpPostedFileBase file, string virtualPath, string physicalPath, string filePath)
{
try
{
//Check directory exis or not
if (!Directory.Exists(physicalPath))
{
Directory.CreateDirectory(physicalPath);
}
//Check file is exist or not
if (!string.IsNullOrWhiteSpace(filePath) && File.Exists(filePath))
{
//Delete Existing file
File.Delete(filePath);
}
//Save new image and update user data
var filename = string.Concat(Guid.NewGuid(), Path.GetExtension(file.FileName));
var savePath = Path.Combine(physicalPath, filename);
file.SaveAs(savePath);
return filename;
}
catch (Exception e)
{
return string.Empty;
}
}
}
}
using ProjectNameSpace.Helpers;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace ProjectNameSpace.Controllers
{
public class SampleController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadFile(HttpPostedFileBase fileObject)
{
var virtualPath = StaticValues.AdvertisementImagePath;
var physicalPath = Server.MapPath(virtualPath);
Utilities.SaveFile(fileObject, virtualPath, physicalPath, "FILE PATH");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment