C#
public ActionResult FileUpload()
{
string relativePath = string.Empty;
if (file != null)
{
// string ImageUniqueName = Guid.NewGuid().ToString();
//string ActualImageName = ImageUniqueName + Path.GetFileName(file.FileName);
string pic = System.IO.Path.GetFileName(file.FileName);
path = System.IO.Path.Combine(Server.MapPath("/images/profile"), pic);
// file is uploaded
file.SaveAs(path);
relativePath = Path.Combine("/images/profile", ActualImageName);
}
return Json(relativePath, JsonRequestBehavior.AllowGet);
}
Vishal JoshiRank #377 · 6.7K reputationPosted Jan 23, 2024, 5:29 AM EST
Hello, Emmanuel ,
Please check you ajax call for request for the API.
Remove Type as json.
Also In parameter it requires file parameter of type HttpPostedFileBase
so it should be like below
public ActionResult FileUpload(HttpPostedFileBase file){}
Thanks
Vishal Joshi
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 22, 2024, 6:52 AM EST
Thank you Naimish, please I will check and revert
Naimish MakwanaRank #324 · 7.7K reputationPosted Jan 22, 2024, 3:44 AM EST
There are a few issues with your code. Here’s a corrected version:
public ActionResult FileUpload(HttpPostedFileBase file) { string relativePath = string.Empty; if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/uploads/"), fileName); file.SaveAs(path); relativePath = Url.Content("~/uploads/" + fileName); } return Json(new { path = relativePath }, JsonRequestBehavior.AllowGet); }In this corrected version:
fileis of typeHttpPostedFileBasewhich represents an uploaded file.file.SaveAs(path).Please make sure to replace
"~/uploads/"with the actual path where you want to save the files on your server. Also, ensure that the server has the necessary write permissions to that directory.Remember, this is a basic example and doesn’t include error handling and file validation (like checking file size, file type etc.) which you should implement in a production environment.
Thanks
Emmmanuel FIADUFERank #947 · 2.2K reputationPosted Jan 24, 2024, 6:44 AM EST
Thank you team for your support