Last active
January 2, 2024 23:20
-
-
Save ankitkanojia/95b3998a3e7f1a1b93f8da048f52c38f to your computer and use it in GitHub Desktop.
Upload/Save media file using HttpPostedFileBase class in C# MVC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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