Using ASP.NET MVC & AJAX to do a file upload and preview image
I am doing what would take me less that 2 hours to do in old ASP.Net Web Forms but has left me stumped in how to implement in ASP.Net MVC.
I am trying to put together a really basic admin site about musicians. a musician has an associated picture of themselves, then some details like name, age, home town alongside the profile picture.
When an admin user creates a musician, the create view has a file upload, and onchange of the file upload, a preview image should appear. The create page also has the form fields for the other inputs.
In the details view, the musician's profile picture should appear alo开发者_Go百科ngside the details.
When in edit mode, again, the existing image should appear, and if the user chooses to change the picture, the picture again will change there on the spot, without reloading the page.
This seems incredibly easy, but I am really struggling to see how the ASP.Net MVC architecture makes this possible without a great deal of work.
This doesn't really have much to do with MVC architecture. I think you might need to research uploading images with AJAX and the limitations there are. There are numerous workarounds using iframes to achieve the result you are trying to get.
What part exactly are you having problems with? To upload a file you start with a form that posts a file and extra properties like this.
<form action="yourcontroller/savefile" method="post" enctype="mulitipart/form-data">
<input type="file" name="file" />
<input type="text" name="other" />
</form>
Then you will need a controller action to handle the post. The file can be bound to a HttpPostedFileBase object which has a method to save it. Other form inputs can also be bound. Finally to display the image you just need to pass the image path to the a view to render it.
public ActionResult SaveFileAction(string other, HttpPostedFileBase file)
{
file.SaveAs("/path/to/save/"); // Note Server.MapPath() converts urls to
// a physical path which might help.
ViewData["path"] = "/url/to/image"; // Add the URL to the view date so we can
// use it in the view
return View();
}
Finally in the view view we can render the uploaded image.
<img src="<%= imageUrl %>" />
Clearly you will have more to consider for your application, but hopefully this helps show that uploading and then displaying images in ASP.NET MVC is not too much work.
精彩评论