gpt4 book ai didi

c# - 如果图像丢失,加载默认图像

转载 作者:行者123 更新时间:2023-12-02 04:47:54 26 4
gpt4 key购买 nike

在我的 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"));
}

关于c# - 如果图像丢失,加载默认图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19438493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com