0

how can i make an uploading image page via razor syntax (CSHTML) to simply upload file to /image root with increasing name like imgxxxyyy.jpg when the img part is fixed and xxx is the id of the inserting/updating product and yyy is the increasing number of image of that product and store the path to the imagpath column in my table ?

more i think about it and i research about it i get more confused .... please help me in this case .

gadfly
  • 42
  • 1
  • 8

1 Answers1

2

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);
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928