首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET MVC 從資料庫讀取圖片並輸出:自訂 ActionResult 與三種替代方案

     編輯:ASP.NET 基礎

方案一:自訂 ImageResult 繼承 ActionResult(最彈性)


public class ImageResult : ActionResult {
    public ImageFormat ContentType { get; set; }
    public Image Image { get; set; }
    public string SourceName { get; set; }

    public ImageResult(string sourceName, ImageFormat contentType) {
        SourceName = sourceName; ContentType = contentType;
    }
    public ImageResult(Image image, ImageFormat contentType) {
        Image = image; ContentType = contentType;
    }

    public override void ExecuteResult(ControllerContext context) {
        var resp = context.HttpContext.Response;
        resp.Clear();
        resp.Cache.SetCacheability(HttpCacheability.NoCache);

        string mime = ContentType.Equals(ImageFormat.Bmp) ? "image/bmp" :
                      ContentType.Equals(ImageFormat.Gif) ? "image/gif" :
                      ContentType.Equals(ImageFormat.Icon) ? "image/vnd.microsoft.icon" :
                      ContentType.Equals(ImageFormat.Jpeg) ? "image/jpeg" :
                      ContentType.Equals(ImageFormat.Png) ? "image/png" :
                      ContentType.Equals(ImageFormat.Tiff) ? "image/tiff" :
                      ContentType.Equals(ImageFormat.Wmf) ? "image/wmf" : "application/octet-stream";
        resp.ContentType = mime;

        if (Image != null) Image.Save(resp.OutputStream, ContentType);
        else resp.TransmitFile(SourceName);
    }
}

Controller 使用


public ActionResult GetPicture(int id) {
    var server = new CategoryServer();
    byte[] buffer = server.GetCategoryPicture(id);
    if (buffer != null) {
        using (var ms = new MemoryStream(buffer)) {
            var img = Image.FromStream(ms);
            return new ImageResult(img, ImageFormat.Jpeg);
        }
    }
    return View(); // 或回傳預設圖片
}

方案二:FileResult 直接輸出實體檔案


public FileResult Image() {
    string path = Server.MapPath("/Content/Images/Decorative/");
    string fileName = Request.Url.Segments.Last();
    string fullPath = Path.Combine(path, fileName);
    return File(fullPath, "image/jpeg");
}

方案三:File 方法簡化版


public ActionResult Image(string id) {
    var dir = Server.MapPath("/Images");
    var path = Path.Combine(dir, id + ".jpg");
    return File(path, "image/jpg");
}

方案四:FileStreamResult 支援大檔案串流(可改造為資料庫讀取)


[AcceptVerbs(HttpVerbs.Get)]
[OutputCache(CacheProfile = "CustomerImages")]
public FileResult Show(int customerId, string imageName) {
    var path = Path.Combine(ConfigData.ImagesDirectory, customerId.ToString(), imageName);
    return new FileStreamResult(new FileStream(path, FileMode.Open), "image/jpeg");
}

方案比較

方案適用場景優點缺點
ImageResult資料庫二進位、動態處理(水印、縮圖)完全控制、支援多種格式程式碼較多
FileResult (實體路徑)靜態檔案、CDN 同步簡潔、自動處理 Range/ETag需實體檔案
File()簡單靜態圖片一行搞定彈性低
FileStreamResult大檔案、資料庫 Blob 串流記憶體友善、支援斷點續傳需手動管理 Stream 生命週期

最佳實務建議

  1. 靜態圖片:直接用 `` 走 IIS 靜態檔案處理,效能最好。
  2. 資料庫圖片:採用 ImageResult 或 FileStreamResult,並加上 OutputCache 快取。
  3. 安全性:避免直接暴露資料庫 ID,改用 GUID 或加密 Token;驗證用戶權限後再輸出。
  4. MIME 類型:嚴格對應副檔名,防止內容嗅探攻擊。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved