

There's quite a bit going on here, so let me walk you through it. Var imageUrl = Path.Combine(uploadDir, ) Var imagePath = Path.Combine(Server.MapPath(uploadDir), )

ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image. ModelState.AddModelError("ImageUpload", "This field is required") Įlse if (!imageTypes.Contains()) Public ActionResult Create(ImageViewModel model) Now, we can create the POST version of our Create action to handle the postback. Now, back to our regularly scheduled program. It'll include properties for things like a title, alt text, a caption, etc. Entityįor this example, we'll be creating an Image type, which will simply be an entity to hold data about an image we upload. Whereas with a simple path reference, you merely drop the URL into your page, and let IIS statically serve the file (which alone is exponentially faster) or you can even offload the file to a CDN for lightning fast delivery to the client. If you store the actual file data in your database, then you must create an action to retrieve that data, write it to a response, add all the appropriate caching and expires headers to that response (for the love of all things good), etc., which also means that the entire ASP.NET machinery must spin up in order to serve that file to the user.

As I like to say: just because you can shoot yourself in the foot with a gun, doesn't mean you should. While SQL Server and other database servers will allow you store blob data, IMHO, this is extremely bad practice. Hopefully, this guide will save other newbies out there the frustrations I went through.įirst, I'll start with the caveat that this methodology is geared towards storing a path reference to a file and not an actual file, itself, in your database.
Get file path of httppostedfilebase how to#
I emphasized that last bit, because I found numerous tutorials and guides that purportedly showed you how to do file uploads in ASP.NET MVC, but they all had the POST action only receiving the upload itself, not a model full of data and a file upload. When I was first starting out in ASP.NET MVC, one of the things I struggled with the most was how to do file uploads while posting additional model data. File Uploads in ASP.NET MVC with View Models Home Subscribe File Uploads in ASP.NET MVC with View Models 06 January 2014 on asp.net-mvc, view-models, uploads, forms
