Было бы проще, если бы вы использовали Guids для имен файлов. Таким образом, вы можете определить модель вида:
public class MyViewModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
представление, содержащее форму, в которой пользователь сможет выбрать файл для загрузки:
@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>
}
и, наконец, контроллер для отображения формы и обработки загрузки:
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);
}
}