jQuery 上传带有重置默认值的图片预览

jQuery upload image previews with reset defaults

我正在尝试为用户上传的图片创建上传预览。我已经完成了大部分我想做的事情(多亏了 Whosebug ...大量的复制粘贴和一些调整)但是因为我不知道 JavaScript,所以我无法让它正常工作。

function uploadPreview(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      if (e.target.result.trim().length == 0) {
        $('#serviceImage').attr('src', 'http://catawbabrewing.com/wp-content/themes/catawba/images/placeholder.png');
      } else {
        $('#serviceImage').attr('src', e.target.result);
      }
    }

    reader.readAsDataURL(input.files[0]);
  }
}

function uploadPreviewExt(input) {
  if (input.trim().length == 0) {
    var previewSrc = '{{CSS_URL}}/images/placeholder.jpg';
  } else {
    var previewSrc = input;
  }

  $('#serviceImage').attr('src', previewSrc);
}

function resetUploadPreview() {
  if (!$('#previousImage').val()) {
    $('#serviceImage').attr('src', 'http://catawbabrewing.com/wp-content/themes/catawba/images/placeholder.png');
  } else {
    $('#serviceImage').attr('src', '{{PROD_IMG}}/'.$('#previousImage').val());
  }
}

$("#mainImage").change(function() {
  uploadPreview(this);
});

$('[name="mainImgExt"]').on('change', function() {
  uploadPreviewExt(this.value);
});

$('#clearUpload').on('click', function() {
  $('#mainImage').val('');

  if ($('#imgExt').val().trim().length == 0) {
    resetUploadPreview();
  } else {
    uploadPreviewExt($('#imgExt').val());
  }
});

$('#clearUploadExt').on('click', function() {
  $('#imgExt').val('');

  if (!$('#mainImage').val()) {
    resetUploadPreview();
  } else {
    uploadPreview($('#mainImage'));
  }
});
pointer {
  cursor: pointer;
}

img.placeholder {
  width: 100px;
  height: 100px;
}
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="//unpkg.com/popper.js@1.12.9/dist/umd/popper.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<div class="form-group p-3 border p-2 rounded m-3">
  <div class="row">
    <div class="col-sm-3 text-center pt-2 border-right">
      <label for="mainImage"><img src="http://catawbabrewing.com/wp-content/themes/catawba/images/placeholder.png" alt="Placeholder" id="serviceImage" class="placeholder img-thumbnail" aria-describedby="imagePreviewHelp" /></label>
      <small id="imagePreviewHelp" class="form-text text-muted">Preview could appear stretched</small>
    </div>
    <div class="col">
      <label for="mainImage">Image</label>
      <div class="input-group mb-3">
        <input type="file" class="form-control border p-1" id="mainImage" name="mainImage" />
        <div class="input-group-append">
          <span class="input-group-text bg-warning text-danger pointer" id="clearUpload">X</span>
        </div>
      </div>
      <div class="input-group mb-3">
        <input type="text" class="form-control" id="imgExt" name="mainImgExt" placeholder="Externel Image" aria-describedby="imageHelp" />
        <div class="input-group-append">
          <span class="input-group-text bg-warning text-danger pointer" id="clearUploadExt">X</span>
        </div>
      </div>
      <small id="imageHelp" class="form-text text-muted">Upload a local image <strong>or</strong> link to an external image.</small>
    </div>
  </div>
</div>

View on JSFiddle

涉及很多 JavaScript(超出我的舒适区,因为我根本不知道)。

JavaScript 可能遇到 HTML 的两个版本。这取决于用户是添加服务还是编辑服务。表单是在 TWIG 的帮助下动态生成的。

在JSFiddle中,有一个版本的表单上传图片部分(如果是添加服务的话)下面是编辑服务的版本。 (添加了隐藏的输入字段 "previousImage" 并且预览是当前图像而不是占位符)

    <div class="form-group p-3 border p-2 rounded">
        <div class="row">
            <div class="col-sm-3 text-center pt-2 border-right">
                <label for="mainImage"><img src="https://logismarketmx.cdnwm.com/ip/eve-maquinaria-mantenimiento-para-gruas-mantenimiento-de-gruas-987423-FGR.jpg" alt="Vinyl" id="serviceImage" class="placeholder img-thumbnail" aria-describedby="imagePreviewHelp" /></label>
                <input type="hidden" name="previousImage" id="previousImage" value="eve-maquinaria-mantenimiento-para-gruas-mantenimiento-de-gruas-987423-FGR.jpg" />
                <small id="imagePreviewHelp" class="form-text text-muted">Preview could appear stretched</small>
            </div>
            <div class="col">
                <label for="mainImage">Image</label>
                <div class="input-group mb-3">
                    <input type="file" class="form-control border p-1" id="mainImage" name="mainImage" />
                    <div class="input-group-append">
                        <span class="input-group-text bg-warning text-danger pointer" id="clearUpload">X</span>
                    </div>
                </div>
                <div class="input-group mb-3">
                    <input type="text" class="form-control" id="imgExt" name="mainImgExt" placeholder="Externel Image" aria-describedby="imageHelp" />
                    <div class="input-group-append">
                        <span class="input-group-text bg-warning text-danger pointer" id="clearUploadExt">X</span>
                    </div>
                </div>
                <small id="imageHelp" class="form-text text-muted">Upload a local image <strong>or</strong> link to an external image.</small>
            </div>
        </div>
    </div>

这就是问题的背景。这就是我正在努力解决的问题。

当用户单击红色 'X' 以清除紧靠左侧的字段时,我需要它。它清除了该字段,但我还想重置上传预览图像。

第二个版本的表单之所以重要是因为如果用户重置并添加,则图像会更改为占位符(本地上传会发生这种情况,但外部上传不会发生这种情况 URL) ;但是,如果用户正在编辑服务,则上传预览将重置为之前为该服务设置的图片。

我有 javascript 我认为应该有效的方法,但它没有。

    function resetUploadPreview()
    {
        if(!$('#previousImage').val())
        {
            $('#serviceImage').attr('src', '{{CSS_URL}}/images/placeholder.jpg');
        }
        else
        {
            $('#serviceImage').attr('src', '{{PROD_IMG}}/' . $('#previousImage').val());
        }
    }

其背后的逻辑是,如果 ID 为 'previousImage' 的输入为空(或不存在),它将显示占位符,但如果它确实有一个值,我们将使用它的值(文件名)来显示它图片。

但它并没有这样做,清除本地文件上传会将图像重置为占位符,无论previousImage是否填充,而外部url根本不会清除。

我想实现的另一个功能是,如果两个字段都已填写(本地和外部),那么清除一个将在预览中显示另一个图像。

抱歉,如果这看起来很简单,逻辑对我来说似乎很简单,但我似乎无法让它工作,我不知道我错过了什么......在我看来一切都在它应该工作的地方, 但事实并非如此。

编辑时它不会重置为上一张图片...它根本不会重置。控制台给我以下错误

    TypeError: "../design/variant/productImages/".$ is not a function

它导致的代码行是:

    function resetUploadPreview()
    {
        if(!$('#previousImage').val())
        {
            $('#serviceImage').attr('src', '{{CSS_URL}}/images/placeholder.jpg');
        }
        else
        {
            // This is the line that makes that error
            $('#serviceImage').attr('src', '{{PROD_IMG}}/' . $('#previousImage').val());
        }
    }

添加新服务时,如果先添加本地图像,然后添加外部图像,它会正常显示外部图像预览。但是一旦你清除外部图像,它应该显示本地图像(因为它已被填充)但它根本不会改变预览。并且控制台没有显示任何 warnings/errors.

我做错了什么?

干得好!
我做了两个调整:

  1. 在 JavaScript 中,string concatenation is performed by using the + sign, as opposed to the . sign. (Hence the TypeError 您引用的消息。)我相应地更改了 resetUploadPreview() 中的代码。

  2. uploadPreview()函数不期望一个jQuery对象,而是传递一个jQuery对象,在清除外部图像字段时恢复主图像.我将其改为传递 DOM 元素:$('#mainImage')[0] 而不是 $('#mainImage')。有关详细信息,请参阅

function uploadPreview(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      if (e.target.result.trim().length == 0) {
        $('#serviceImage').attr('src', '//catawbabrewing.com/wp-content/themes/catawba/images/placeholder.png');
      } else {
        $('#serviceImage').attr('src', e.target.result);
      }
    }

    reader.readAsDataURL(input.files[0]);
  }
}

function uploadPreviewExt(input) {
  if (input.trim().length == 0) {
    var previewSrc = '{{CSS_URL}}/images/placeholder.jpg';
  } else {
    var previewSrc = input;
  }

  $('#serviceImage').attr('src', previewSrc);
}

function resetUploadPreview() {
  if (!$('#previousImage').val()) {
    $('#serviceImage').attr('src', 'http://catawbabrewing.com/wp-content/themes/catawba/images/placeholder.png');
  } else {
    $('#serviceImage').attr('src', '{{PROD_IMG}}/' + $('#previousImage').val());
  }
}

$("#mainImage").change(function() {
  uploadPreview(this);
});

$('[name="mainImgExt"]').on('change', function() {
  uploadPreviewExt(this.value);
});

$('#clearUpload').on('click', function() {
  $('#mainImage').val('');

  if ($('#imgExt').val().trim().length == 0) {
    resetUploadPreview();
  } else {
    uploadPreviewExt($('#imgExt').val());
  }
});

$('#clearUploadExt').on('click', function() {
  $('#imgExt').val('');

  if (!$('#mainImage').val()) {
    resetUploadPreview();
  } else {
    uploadPreview($('#mainImage')[0]);
  }
});
pointer {
  cursor: pointer;
}

img.placeholder {
  width: 100px;
  height: 100px;
}
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="//unpkg.com/popper.js@1.12.9/dist/umd/popper.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<div class="form-group p-3 border p-2 rounded m-3">
  <div class="row">
    <div class="col-sm-3 text-center pt-2 border-right">
      <label for="mainImage"><img src="http://catawbabrewing.com/wp-content/themes/catawba/images/placeholder.png" alt="Placeholder" id="serviceImage" class="placeholder img-thumbnail" aria-describedby="imagePreviewHelp" /></label>
      <small id="imagePreviewHelp" class="form-text text-muted">Preview could appear stretched</small>
    </div>
    <div class="col">
      <label for="mainImage">Image</label>
      <div class="input-group mb-3">
        <input type="file" class="form-control border p-1" id="mainImage" name="mainImage" />
        <div class="input-group-append">
          <span class="input-group-text bg-warning text-danger pointer" id="clearUpload">X</span>
        </div>
      </div>
      <div class="input-group mb-3">
        <input type="text" class="form-control" id="imgExt" name="mainImgExt" placeholder="Externel Image" aria-describedby="imageHelp" />
        <div class="input-group-append">
          <span class="input-group-text bg-warning text-danger pointer" id="clearUploadExt">X</span>
        </div>
      </div>
      <small id="imageHelp" class="form-text text-muted">Upload a local image <strong>or</strong> link to an external image.</small>
    </div>
  </div>
</div>