jQuery 图像错误 - 如果原始图像不存在,则显示不同的图像引导文件输入

问题描述

我正在使用 (Bootstrap File Input) 组件进行文件上传,这很有用。我已经定义了 initialPreviewConfig 以在服务器上显示现有图像,但有时给定用户没有文件,所以我需要显示一个图像,通常在 HTML 中我会使用下面的错误,但这不起作用,正确的是因为我不够聪明,无法找到正确的数字或​​“&”的组合(尝试了很多!) .. 但 maeby 因为这在 JS 中不起作用.. 谁能帮我找到解决方案?

我在下面的 JS 中尝试过的错误

onerror="this.src='https://example.com/img/missing.jpg'"

我的来源:

$("#input-fas").fileinput({
    theme: "fas",uploadUrl: "/file-upload-batch/2",allowedFileExtensions: ['jpg'],overwriteInitial: false,maxFileSize:2000,maxFilesNum: 1,language: "da",initialPreview: [
    "<img src='/profile_pictures/web/<%=Request.QueryString("initials")%>.jpg' class='file-preview-image' alt='Nuværende' title='Nuværende' onerror='this.src=''https://example.com/img/missing.jpg'' style='width: 75%'>",],// initial preview configuration
initialPreviewConfig: [
    {
        caption: 'Nuværende (<%=Request.QueryString("initials")%>.jpg)',width: '120px',frameAttr: {
            title: 'Nuværende',},}
],slugCallback: function (filename) {
        return filename.replace('(','_').replace(']','_');
    },});
<div style="width: 550px;">
    <input id="input-fas" name="input-fas[]" type="file" multiple>
</div>

解决方法

看起来您应该先检查文件是否存在,如果不存在则使用默认路径。我在这里使用 JSP(?我猜,您没有标记您的后端语言)超出了我的驾驶能力,但我找到了 this 并试图使其适应您的需求。这在逻辑上是合理的,但我不知道它是否有效,也无法对其进行测试。

ServletContext app = getServletContext();
String path1 = app.getRealPath("/profile_pictures/web/<%=Request.QueryString("initials")%>.jpg");
File theImage1 = new File(path1);

String imageURL1 = "https://example.com/img/missing.jpg";

if(theImage1.exists())
{
    imageURL1 = "/profile_pictures/web/<%=Request.QueryString("initials")%>.jpg";
}

...

initialPreview: [
    "<img src='<%=imageURL1%>' class='file-preview-image' alt='Nuværende' title='Nuværende' style='width: 75%'>",],
,

在@Arleigh Hix 的 postet 示例之后,虽然该脚本是 JSP 而不是 ASP,但他的逻辑让我思考..所以我最终使用了文件系统对象和您在下面看到的结果工作代码:

Dim ProfileImage,path,fso

path = "img/profile_pictures/web/" & Request.Querystring("initials") & ".jpg"

Set fso = CreateObject("Scripting.FileSystemObject")

If fso.FileExists(Server.MapPath(path)) Then
   ProfileImage = path
Else
   ProfileImage = "img/profile_pictures/web/missing.jpg"
End If

Set fso = Nothing