首页 > 解决方案 > 使用 MVC 的布局页面中的动态徽标图像

问题描述

我只是在制作简单的网络应用程序,用户可以在其中上传徽标图像文件以使用 MVC 放置在布局页面中。如果用户上传了新的徽标图像文件,它将替换以前的图像文件,并在下次刷新时显示。但我不知道哪种方式优雅。

目前,当用户上传标志图像时,图像的本地路径和相关信息都保存在数据库中。

在布局页面中,

 <img src="@Url.Action("GetLogo","BaseController")" alt="Logo"/>

从数据库中检索保存的本地路径的操作“GetLogo”并返回 FileContentResult,如下所示

 public FileContentResult GetLogo(string param)
 {
    //retrieving path from db
    //return new FileContentResult(bytes, "image");
 }

这现在工作正常。但它似乎效率较低,因为每次用户移动时,布局页面也会刷新,并且必须进行一些数据库查询以获取路径信息。

我能想到的另一种方式是应该使用静态文件名,如下所示。

<img src="@Url.Content("~/Content/logo.png")" alt="Logo"/>

因此,当用户上传新的标志文件时,服务器必须将新标志图像文件的名称更改为 logo.png。但我不确定当用户上传不同的文件类型(如 jpeg 和 gif)时它会起作用。

就服务器而言,数据库查询可能不是负担。所以我可能会坚持使用第一种方法。但我不确定。如果任何有经验的人可以给我任何提示,我将不胜感激。谢谢,

标签: htmlcssasp.net-mvcdynamic

解决方案


您可以将徽标路径存储在会话中并仅在用户登录时刷新

检查此代码

    public string GetLogo(string param)
    {
        string imagePath = "~/Content/Logo.png";//retrieve path from db here
        string filePathActual = Server.MapPath(imagePath);
        //put flag in DB isOverWritten
        if (isOverWritten)//only if image is overwritten in db then we write into the file
        {
            System.IO.File.WriteAllBytes(filePathActual,bytes);//this will refresh your image
        }

        return imagePath;
    }

推荐阅读