I'm working on a ASP.NET MVC site that will allow a user to upload multiple images to a gallery. After a user uploads their images and before they are saved to the database, the user will have the ability to reorder the images using a jQuery drag and drop. The user can then submit their uploads. The user will also have the ability later on to edit their gallery and again have the ability to reshuffle the order of their images. I will not be saving the images to the database, just the filenames. I'm not sure how to best handle this. I'm thinking the POST controller will take a List<HttpPostedFileBase> parameter, and then convert to a byte [] array to maintain the image order. Then save the image names to the database as a comma separated string? What would the most efficient way to handle this be?
1 Answer
Alright so if we put drag and drop a side, see this as your view:
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="file" name="files" value="" multiple="multiple"/> <input type="submit" value="Upload"/> } In your controller:
[HttpPost] public ActionResult Index(HttpPostedFileBase[] files) { try { foreach (HttpPostedFileBase file in files) { string name = System.IO.Path.GetFileName(file.FileName); file.SaveAs(Server.MapPath("~/Images/" + name)); string filename = "Images/" + name; //Save the the filename to your database } } catch { throw ex; } return View(); } 2 Comments
PixelPaul
Thank you for posting this. I basically understand this part of it, what I was trying to get at was what is the best method for keeping track of the order of the images. For example, a user uploads 4 images: pic1.jpg, pic2.jpg, pic3.jpg, pic4.jpg. Then shuffles the order of the images to: pic4.jpg, pic1.jpg, pic 3.jpg, pic2.jpg. How do I write the image names to the DB so when I read from the DB and display in the view, the images are in the correct order as specified by the user?
Masoud Andalibi
@PixelPaul Indeed. what Stephen Muecke said is the best practice.
int Orderso that you can sort them byOrder. And then in what ever plugin your using to drag and drop/rearrange the images, you can update theOrderproperty and save back to the database.