【问题标题】:Handling images using MVC3使用 MVC3 处理图像
【发布时间】:2012-07-21 18:26:15
【问题描述】:

使用 MVC3 在 Web 服务器上处理图像的最佳方法是什么。有没有这方面的最佳实践?通过处理图像,我的意思是让用户能够将照片上传到网络服务器上,将它们保存在磁盘上,并在必要时检索它们以显示在页面上。

【问题讨论】:

    标签: c# asp.net-mvc-3 image upload webserver


    【解决方案1】:

    使用存储在数据库中的路径将图像保存到磁盘通常是最好和最快的方法。上传可以通过任何常规方式处理,但有一些很好的开源库可以帮助您(plupload 是我使用过的最完整的功能)。

    您可以创建自己的ActionResult 实现并返回和显示图像。您的控制器操作可以采用识别图像所需的任何参数,然后您可以从磁盘中检索它并从您的操作中返回 ImageResult

    这是一个基本的实现(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); 
        } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 2015-08-21
      • 1970-01-01
      相关资源
      最近更新 更多