It would be easier if you used Guids for filenames. So you could define a view model:
public class MyViewModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
a view containing a form where the user will be able to select a file to upload:
@model MyViewModel
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.LabelFor(x => x.File)
@Html.TextBoxFor(x => x.File, new { type = "file" })
@Html.ValidationMessageFor(x => x.File)
<button type="submit">Upload</button>
}
and finally a controller to show the form and process the upload:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (model.File != null && model.File.ContentLength > 0)
{
var imageFolder = Server.MapPath("~/image");
var ext = Path.GetExtension(model.File.FileName);
var file = Path.ChangeExtension(Guid.NewGuid().ToString(), ext);
var fullPath = Path.Combine(imageFolder, file);
model.File.SaveAs(fullPath);
// Save the full path of the uploaded file
// in the database. Obviously this code should be externalized
// into a repository but for the purposes of this example
// I have left it in the controller
var connString = ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString;
using (var conn = new SqlConnection(connString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "INSERT INTO images VALUES (@path)";
cmd.Parameters.AddWithValue("@path", fullPath);
cmd.ExecuteNonQuery();
}
}
return View(model);
}
}