Reputation: 1615
what are some best approaches for handling images on a web server using MVC3. Are there any best practices for this? By handling images, I mean enabling users to upload photos on a web server, saving them on the disk, and retrieving them when necessary to display on a page.
Upvotes: 0
Views: 658
Reputation: 28699
Saving the images to disk with the path stored in a database is usually the best and fastest approach. Uploading can be handled by any regular means, but there a few good open source libraries to help you out (plupload is the fullest featured I've used).
You can create you own ActionResult
implementation and return and image to display. Your controller action can take whatever parameters you need to identify your image, you can then retrieve it from disk and return an ImageResult
from your action.
Here is a basic implementation (credit):
public class ImageResult : ActionResult
{
public ImageResult() { }
public Image Image { get; set; }
public ImageFormat ImageFormat { get; set; }
public override void ExecuteResult(ControllerContext context)
{
// verify properties
if (Image == null)
{
throw new ArgumentNullException("Image");
}
if (ImageFormat == null)
{
throw new ArgumentNullException("ImageFormat");
}
// output
context.HttpContext.Response.Clear();
if (ImageFormat.Equals(ImageFormat.Bmp)) context.HttpContext.Response.ContentType = "image/bmp";
if (ImageFormat.Equals(ImageFormat.Gif)) context.HttpContext.Response.ContentType = "image/gif";
if (ImageFormat.Equals(ImageFormat.Icon)) context.HttpContext.Response.ContentType = "image/vnd.microsoft.icon";
if (ImageFormat.Equals(ImageFormat.Jpeg)) context.HttpContext.Response.ContentType = "image/jpeg";
if (ImageFormat.Equals(ImageFormat.Png)) context.HttpContext.Response.ContentType = "image/png";
if (ImageFormat.Equals(ImageFormat.Tiff)) context.HttpContext.Response.ContentType = "image/tiff";
if (ImageFormat.Equals(ImageFormat.Wmf)) context.HttpContext.Response.ContentType = "image/wmf";
Image.Save(context.HttpContext.Response.OutputStream, ImageFormat);
}
}
Upvotes: 1