Change Image extension using FileUpload control in ASP.Net MVC

Last Reply 14 days ago By arunkurmi

Posted 14 days ago

How to change image extension to jpeg format after uploading via uploadfile control and save it as jpeg format.

        [HttpGet]
		public ActionResult UploadFile()
		{
			return View();
		}
		[HttpPost]
		public ActionResult UploadFile(HttpPostedFileBase file)
		{
			try
			{
				if (Request.Files.Count > 0)
				{
					HttpPostedFileBase File = Request.Files[0];
					if (File != null && File.ContentLength > 0)
					{
						if (Path.GetExtension(file.FileName) != "jpeg")
						{
							string trailingPath = Path.GetFileName(file.FileName);
							string fullPath = Server.MapPath(file.FileName.Replace("png","jpeg"));
							file.SaveAs(fullPath);

 

@{
	ViewBag.Title = "UploadFile";
}

<h2>UploadFile</h2>

@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

<div>
	<input id="File" name="File" type="file" style="width:100%" accept="image/*" />
	<input type="submit" value="Upload" />
	@ViewBag.Message
</div>
} 

 

Posted 14 days ago
Lipi says:
string fullPath = Server.MapPath(FileName.Replace("png","jpeg"));

 Replace with below line.

 string fullPath = Server.MapPath("~/")+file.FileName.Replace("png","jpeg");