通过javascript处理默认配置文件图像的更好方法

时间:2013-09-17 08:22:33

标签: javascript image

var imgRoot='forum/attachments/users/';

<img 
 src="../employees/attachments/users/username_xyz.png" 
 onerror='this.src=imgRoot+"no_profile_pic.png" '
/>

我必须显示用户个人资料图片(未在db中设置),只需普通上传到预定义目录,用户名中的下划线替换空格,例如用户名为'ABC',我们期待图像A_B_C.png 。当用户没有图像时会出现问题,我们必须显示默认图像,如上所示,添加一个onerror事件来加载默认图像。

有没有更好的方法来处理这个问题?我们事先并不知道用户是否有个人资料图片上传。另一个烦恼是,在加载回退默认配置文件图像之前,如果找不到用户配置文件图像,则firebug会报告网络错误。

3 个答案:

答案 0 :(得分:1)

当找不到文件时,我会让服务器使用http 302重定向到默认配置文件图像网址。大多数Web服务器都可以在没有任何代码的情况下执行此操作,只需配置文件。

编辑:由于您正在使用Apache,因此您需要执行以下操作:

  1. 确保已安装mod_rewrite。
  2. 如果您要使用.htaccess文件,请确保为目标目录设置了AllowOverride On
  3. 修改您的httpd.conf.htaccess文件。

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^.*$ /anonymous.jpg [L,R=302]
    
  4. Apache配置有很多怪癖,所以你的配置可能会略有不同。

答案 1 :(得分:1)

您还可以使用Javascript预加载图片。加载图像时,请将其粘贴。如果失败则做其他事情,比如提供后备。这里有一个JS代码片段,显示了一个可能的解决方案:

/**
 * Tries to load an image and renders a fallback image if it fails.
 * @param {string} srcImage The source of the image to load.
 * @param {string} srcFallback The source of the fallback image.
 */
function loadImageOrFallback(srcImage, srcFallback) {
  var image = new Image(),
      timerFallback = null,
      hasRenderedFallbackImage = false;

  image.onload = function() {
    if (timerFallback !== null) {
      clear(timerFallback);
    }

    if (hasRenderedFallbackImage) {
       // replace the fallback image
    } else {
      // append image to wherever you want
    }
  };

  image.src = srcImage;

  // since there is no way to detect an error when preloading the image,
  // you can use a timeout function (here we are waiting 2 seconds)

  timerFallback = setTimeout(function() {
    var fallbackImage = new Image();
    fallbackImage.src = srcFallback;

    // append fallbackImage to wherever you want

    hasRenderedFallbackImage = true;

  }, 2000);
}

loadImageOrFallback('A_B_C.png', 'fallback.png');

使用JavaScript检查这一点遵循尝试错误的方法。超时也引入了一些延迟。如果您能在服务器端检测到这种情况,那就更好了。

请注意,渲染后备图像后可能会加载图像。这就是我们存储附加后备图像的原因,并在onload回调中检查其值。

我准备了this jsFiddle,说明了如何使用它。

答案 2 :(得分:0)

您可以让Web应用程序检查文件系统并查看该文件是否存在。不知道你的网络应用程序是什么内置的。例如:http://www.php.net/manual/en/function.file-exists.php

在JS中做这件事很糟糕。它总是试图加载图像。