如果缺少图像,请加载默认图像

本文关键字:图像 加载 默认 如果 | 更新日期: 2023-09-27 18:35:55

在我的 asp.net 网站上,我正在动态构建某些页面。 我从服务器加载了某些图像。 如果图像不存在,那么我需要加载默认图像。

到目前为止,我一直在检查 url 是否有效,如果是,那么我知道图像存在。 如果 url 无效,那么我知道在我的代码中提供我的默认图像。 为此,我做了这个:

    //returns true if the url actually exists
    //however, this will ALWAYS throw an exception if it exists, so beware the debugger.
    public static bool IsValidUrl(string url) {
        HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
        httpReq.AllowAutoRedirect = false;
        httpReq.Method = "HEAD";
        httpReq.KeepAlive = false;
        httpReq.Timeout = 2000;
        HttpWebResponse httpRes = default(HttpWebResponse);
        bool exists = false;
        try {
            httpRes = (HttpWebResponse)httpReq.GetResponse();
            if (httpRes.StatusCode == HttpStatusCode.OK) {
                exists = true;
            }
        } catch {
        }
        return exists;
    }

但这并不是一个好方法,我不喜欢必须证明这样的异常。 此外,如果我添加新图像,服务器不会认为新图像是有效的 url,直到经过一段时间(或者我在 IIS 中重新启动网站) - 这是导致我寻找另一种方法的错误。

有没有更好的方法来提供默认图像,以便在我选择的图像不存在时显示?

如果缺少图像,请加载默认图像

如果可以使用客户端解决方案,这可能适合您:

<img src="fakesrc" onerror="setDefaultImage(this);" />

函数:

function setDefaultImage(img)
{
    //set default.
    img.src="https://www.google.com/images/srpr/logo11w.png";
}

img 将尝试从其原始 src 属性加载,如果图像不存在,它将触发 onerror 事件。setDefaultImage() 方法会将图像设置为默认图像。http://jsfiddle.net/Q64hn/

编辑

如果文件在您的服务器中,您可以让文件系统处理:

public static bool IsValidUrl(string url) {
    return System.IO.File.Exists(HttpContext.Current.Request.MapPath(url));
}

你可以这样称呼它:

protected void Page_Load(object sender, EventArgs e)
{
    bool x = IsValidUrl(ResolveUrl("~/Default.aspx"));
}