Рендеринг изображения с SQL Server в ASP.NET MVC - PullRequest
0 голосов
/ 10 мая 2009

Я пытаюсь извлечь изображение из SQL Server (да, тип данных - изображение) и отобразить его в виде в моем приложении ASP.NET MVC. Кто-нибудь знает, как это можно сделать? Рабочий пример был бы оценен.

Ответы [ 2 ]

3 голосов
/ 10 мая 2009

Мое приложение использует эту функцию:

    //
    // GET: /FileManager/GetFile/ID
    //[CompressFilter(Order = 1)]
    [OutputCache(Order = 2, Duration = 600, VaryByParam = "ID")]
    //[OutputCache(Duration = 600, VaryByParam = "ID", Location = System.Web.UI.OutputCacheLocation.ServerAndClient)]
    public ActionResult GetFile(int ID)
    {
        FileService svc = new FileService(new SqlFileRepository(base.ConnectionString));

        KsisOnline.Data.File result = svc.GetFileByID(ID);

        return File(result.Data, result.MimeType, result.UploadFileName);
    }

.. как вы можете видеть по комментариям, моя самая большая проблема до сих пор заключалась в кэшировании результата изображения. (кстати: метод называется GetFile потому что он возвращает изображения, PDF-файлы и другие)

У меня также есть несколько помощников, которые я использую для визуализации изображений, и их варианты для изображений, поступающих из БД:

    public static string Image(this HtmlHelper helper,
        string classText, string sourcePath, string altText, string width, string height)
    {
        return Image(helper, classText, sourcePath, altText, width, height, null);
    }

    public static string Image(this HtmlHelper helper,
        string classText, string sourcePath, string altText, string width, string height, object htmlAttributes)
    {
        StringBuilder sb = new StringBuilder();
        if (htmlAttributes != null)
            foreach (PropertyInfo p in htmlAttributes.GetType().GetProperties())
                sb.AppendFormat(@" {0}=""{1}""", p.Name, p.GetValue(htmlAttributes, null).ToString());

        if (htmlAttributes == null)
            return String.Format(@"<img{0} src=""{1}"" alt=""{2}"" width=""{3}"" height=""{4}"" />",
                String.IsNullOrEmpty(classText) ? String.Empty : String.Format(@" class=""{0}""", classText),
                (new UrlHelper(helper.ViewContext.RequestContext)).Content(sourcePath),
                altText, width, height);
        else
            return String.Format(@"<img{0} src=""{1}"" alt=""{2}"" width=""{3}"" height=""{4}""{5} />",
                String.IsNullOrEmpty(classText) ? String.Empty : String.Format(@" class=""{0}""", classText),
                (new UrlHelper(helper.ViewContext.RequestContext)).Content(sourcePath),
                altText, width, height, sb.ToString());
    }

    public static string DBImage(this HtmlHelper helper,
      string classText, int fileID, string altText, string width, string height)
    {
        return DBImage(helper, classText, fileID, altText, width, height, null);
    }

    public static string DBImage(this HtmlHelper helper,
        string classText, int fileID, string altText, string width, string height, object htmlAttributes)
    {
        return Image(helper, classText, @"/FileManager/GetFile/" + fileID.ToString(),
            altText, width, height, htmlAttributes);
    }

.. помощники DBImage - это те, которые используют действие GetFile.

1 голос
/ 10 мая 2009

Создание пользовательского результата - самый чистый способ справиться с этим, вот хороший пример:

http://blog.maartenballiauw.be/post/2008/05/ASPNET-MVC-custom-ActionResult.aspx

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...