How can i add image path in database, while image in the project folder using ASP.NET MVC C#??
As asked on facebook group
C# code in Controller to save image file in folders and it's path in database
[HttpPost]
public ActionResult ImageUpload()
{
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
var savedurl = "";
for (int i = 0; i < files.Count; i++)
{
//use this if you have multiple files, otherwise leave it commented
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
string subPath = "~/Images/Upload/" + DateTime.Now.ToString("dd-MM-yyyy")+"/"; // your code goes here
bool exists = System.IO.Directory.Exists(Server.MapPath("~/Images/Upload/"+DateTime.Now.ToString("dd-MM-yyyy")+"/"));
if (!exists)
{ System.IO.Directory.CreateDirectory(Server.MapPath("~/Images/Upload/" + DateTime.Now.ToString("dd-MM-yyyy") + "/")); }
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Images/Upload/" + DateTime.Now.ToString("dd-MM-yyyy")+"/"), fname);
savedurl = "/Images/Upload/" + DateTime.Now.ToString("dd-MM-yyyy")+"/" + file.FileName;
file.SaveAs(fname);
using(var context= new DatabaseConnection())
{
//Save savedurl in database
}
}
// Returns message that successfully uploaded
return Json(new { MSG="File Uploaded Successfully!" , SAvedUrl= savedurl },JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
HTML
<input name="image" type="file" id="upload" accept="image/*" />
jQuery:
$('#upload').on('change', function () {
//Change this line for multiple image upload
var file = this.files[0];
var files = this.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
$.ajax({
url: '/Controller/ImageUpload',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert( result.SavedUrl);
},
error: function (err) {
// alert(err.statusText);
}
});
});
The above code can handle multiple file uploads, but you would have to change the code accordingly, for now, it will upload single image file only.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly