提问者:小点点

src和背景图像的jQuery-Image上传器


我有一个图像上传程序使用src处理图像,但是如果我将图像更改为具有background-imagediv,则上传程序无法读取该文件,因为它不是来自src。

我希望上传程序能够检测.file-image是否正在使用srcvsbackground-image,并相应地更新图像。

目前,只有第二个上传程序可以在文件映像是带有src的映像的情况下工作。 如何启用第一个使用background-image而不是imgsrc的上传程序?

null

$(function() {
  $(".file-drag").click(function(event) {
    $(this).siblings(".file-upload").click();
  });
  $(".uploader--src").each(function() {
    var imageNote = $(this).find(".start"),
      image = $(this).find(".file-image");
    if (image.attr("src").length > 0) {
      imageNote.addClass("hidden");
      image.removeClass("hidden");
    } else {
      imageNote.removeClass("hidden");
      image.addClass("hidden");
    }
  });
  $(".uploader--bg").each(function() {
    var imageNote = $(this).find(".start"),
      image = $(this).find(".file-image"),
      imageBg = $(this).closest(".uploader--bg").find(".file-image");
    if (imageBg.css("background-image") != "") {
      imageNote.addClass("hidden");
      imageBg.removeClass("hidden");
    } else {
      imageNote.removeClass("hidden");
      imageBg.addClass("hidden");
    }
  });

  function ekUpload(item) {
    var form = $(this).find("form.uploader"),
      fileSelect = $(this).find(".file-upload"),
      fileDrag = $(this).find(".file-drag"),
      submitButton = $(this).find(".submit-button");

    function Init() {
      $(document).on("change", "form", function(e) {
        fileSelectHandler(e);
      });

      // Is XHR2 available?
      var xhr = new XMLHttpRequest();
      if (xhr.upload) {
        if (isAdvancedUpload) {
          $(document)
            .on(
              "drag dragstart dragend dragover dragenter dragleave",
              "form",
              function(e) {
                // fileDragHover(e);
                e.preventDefault();
                e.stopPropagation();
              }
            )
            .on("dragover dragenter", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              $(e.target).addClass("is-dragover");
            })
            .on("dragleave dragend drop", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              $(e.target).removeClass("is-dragover");
            })
            .on("drop dragover", "body", function(e) {
              e.preventDefault();
              e.stopPropagation();
            })
            .on("drop", "form", function(e) {
              e.preventDefault();
              e.stopPropagation();
              fileSelectHandler(e);
            });
        }
      }
    }

    function fileDragHover(e) {
      e.stopPropagation();
      e.preventDefault();
      e.target.className =
        e.type === "dragover" ? "hover" : "modal-body file-upload";
    }

    async function fileSelectHandler(e) {
      var theForm = $(e.target).parent("form.uploader");

      var files = e.target.files || e.originalEvent.dataTransfer.files;

      // Process all File objects
      for (let i = 0; i < files.length; i++) {
        const f = files[i];
        if (
          theForm.closest(".checkalpha").length === 0 ||
          (await hasAlpha(f))
        ) {
          parseFile(f, theForm);
          uploadFile(f, theForm);
        } else {
          $(theForm)
            .closest(".checkalpha")
            .find(".response, .error-image")
            .removeClass("hidden");
          $(theForm).find(".file-image, .start").addClass("hidden");
          output(
            '<strong class="warning">Image background is not transparent</strong>'
          );
        }
      }
    }

    // Output
    function output(msg) {
      // Response
      var m = $(item).find(".message");
      m.html(msg);
    }

    function hasAlpha(file) {
      return new Promise((resolve, reject) => {
        let hasAlpha = false;
        const canvas = document.querySelector("canvas");
        const ctx = canvas.getContext("2d");

        const img = new Image();
        img.crossOrigin = "Anonymous";
        img.onerror = reject;
        img.onload = function() {
          canvas.width = img.width;
          canvas.height = img.height;

          ctx.drawImage(img, 0, 0);
          const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height)
            .data;

          for (let j = 0; j < imgData.length; j += 4) {
            if (imgData[j + 3] < 255) {
              hasAlpha = true;
              break;
            }
          }
          resolve(hasAlpha);
        };
        img.src = URL.createObjectURL(file);
      });
    }

    function parseFile(file, thisForm) {
      output("<strong>" + encodeURI(file.name) + "</strong>");

      // var fileType = file.type;
      // console.log(fileType);
      var imageName = file.name;

      var isGood = /\.(?=svg|jpg|png|jpeg)/gi.test(imageName);
      if (isGood) {
        $(thisForm).find(".start, .notimage").addClass("hidden");
        $(thisForm).closest(".checkalpha").find(".response").addClass("hidden");
        $(thisForm).find(".error-image").addClass("hidden");
        $(thisForm)
          .find("label.has-advanced-upload")
          .removeClass("has-advanced-upload");
        $(thisForm)
          .find(".file-image")
          .removeClass("hidden")
          .attr("src", URL.createObjectURL(file));
      } else {
        $(thisForm).find(".error-image").removeClass("hidden");
        $(thisForm)
          .closest(".checkalpha")
          .find(".response, .file-image")
          .addClass("hidden");
        $(thisForm).find(".file-upload-form").trigger("reset");
        $(thisForm)
          .find('label[for="file-upload"]')
          .addClass("has-advanced-upload");
      }
    }

    function uploadFile(file, thisForm) {
      var xhr = new XMLHttpRequest(),
        fileSizeLimit = 1024; // in MB

      if (xhr.upload) {
        // Check if file is less than x MB
        if (file.size <= fileSizeLimit * 1024 * 1024) {
          // File received / failed
          xhr.onreadystatechange = function(e) {
            if (xhr.readyState == 4) {
              // Everything is good!
            }
          };

          // Start upload
          xhr.open(
            "POST",
            $(thisForm).find(".file-upload-form").attr("action"),
            true
          );
          xhr.setRequestHeader("X-File-Name", file.name);
          xhr.setRequestHeader("X-File-Size", file.size);
          xhr.setRequestHeader("Content-Type", "multipart/form-data");
          xhr.send(file);
        } else {
          output("Please upload a smaller file (< " + fileSizeLimit + " MB).");
        }
      }
    }

    // Check for the various File API support.
    if (window.File && window.FileList && window.FileReader) {
      Init();
    } else {
      document.getElementById("file-drag").style.display = "none";
    }
  }

  var isAdvancedUpload = (function() {
    var div = document.createElement("div");
    return (
      ("draggable" in div || ("ondragstart" in div && "ondrop" in div)) &&
      "FormData" in window &&
      "FileReader" in window
    );
  })();

  if (isAdvancedUpload) {
    $(".file-drag").addClass("has-advanced-upload");
  }

  $(".uploader").each(function() {
    ekUpload(this);
  });
});
@import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css);
@import url("https://fonts.googleapis.com/css?family=Roboto");
body {
  padding: 2rem;
  background: #f8f8f8;
}

img.error-image {
  max-height: 160px;
}

.uploader {
  display: block;
  clear: both;
  margin: 0 auto;
  width: 100%;
  max-width: 600px;
}

.uploader label {
  float: left;
  clear: both;
  width: 100%;
  padding: 2rem 1.5rem;
  text-align: center;
  background: #fff;
  border-radius: 7px;
  border: 3px solid #eee;
  transition: all 0.2s ease;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  cursor: pointer;
}

.uploader label.has-advanced-upload {
  background-color: white;
  outline: 2px dashed lightgrey;
  outline-offset: -10px;
}

.uploader label:hover {
  border: 3px solid #454cad;
  box-shadow: inset 0 0 0 6px #eee;
}

.uploader label.is-dragover,
.uploader label.is-dragover:hover {
  background-color: #eef;
}

.uploader label:hover {
  border: 3px solid #454cad;
  box-shadow: inset 0 0 0 6px #eee;
}

.uploader label:hover .start i.fa {
  -webkit-transform: scale(0.8);
  transform: scale(0.8);
  opacity: 0.3;
}

.uploader .start {
  float: left;
  clear: both;
  width: 100%;
  pointer-events: none;
}

.uploader .start.hidden {
  display: none;
}

.uploader .start i.fa {
  font-size: 50px;
  margin-bottom: 1rem;
  transition: all 0.2s ease-in-out;
}

.uploader .response {
  float: left;
  clear: both;
  width: 100%;
}

.uploader .response.hidden {
  display: none;
}

.uploader .response .messages {
  margin-bottom: 0.5rem;
}

.uploader .file-image {
  pointer-events: none;
  margin: 0 auto 0.5rem auto;
  width: auto;
  height: auto;
  max-width: 180px;
}

.uploader--bg .file-image {
  border-radius: 9px;
  min-height: 120px !important;
  min-width: 120px !important;
  padding: 0 0.6rem;
  background-size: cover !important;
  background-repeat: no-repeat !important;
  background-position: center !important;
}

.uploader .file-image.hidden {
  display: none;
}

.uploader .notimage {
  display: block;
  float: left;
  clear: both;
  width: 100%;
}

.uploader .notimage.hidden {
  display: none;
}

.uploader progress,
.uploader .progress {
  display: inline;
  clear: both;
  margin: 0 auto;
  width: 100%;
  max-width: 180px;
  height: 8px;
  border: 0;
  border-radius: 4px;
  background-color: #eee;
  overflow: hidden;
}

.uploader .progress[value]::-webkit-progress-bar {
  border-radius: 4px;
  background-color: #eee;
}

.uploader .progress[value]::-webkit-progress-value {
  background: linear-gradient(to right, #393f90 0%, #454cad 50%);
  border-radius: 4px;
}

.uploader .progress[value]::-moz-progress-bar {
  background: linear-gradient(to right, #393f90 0%, #454cad 50%);
  border-radius: 4px;
}

.uploader input[type="file"] {
  display: none;
}

.uploader div {
  margin: 0 0 0.5rem 0;
  color: #5f6982;
}

.uploader .btn {
  display: inline-block;
  margin: 0.5rem 0.5rem 1rem 0.5rem;
  clear: both;
  font-family: inherit;
  font-weight: 700;
  font-size: 14px;
  text-decoration: none;
  text-transform: initial;
  border: none;
  border-radius: 0.2rem;
  outline: none;
  padding: 0 1rem;
  height: 36px;
  line-height: 36px;
  color: #fff;
  transition: all 0.2s ease-in-out;
  box-sizing: border-box;
  background: #454cad;
  border-color: #454cad;
  cursor: pointer;
}

.uploader input[type="file"],
.hidden {
  display: none;
}

input[type="file"].hidden {
  display: block;
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}

.warning {
  color: red;
  font-weight: bold;
}

canvas {
  position: absolute;
  top: -2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Upload  -->
<div class="">
  <form class="file-upload-form uploader uploader--bg">
    <input class="file-upload" type="file" name="fileUpload" accept="image/*" />
    <label for="file-upload" class="file-drag">
      <div class="file-image" style="background-image: url('https://uploads-ssl.webflow.com/59df9e77ad9420000140eafe/5d379cfa511d417099a53de4_Giraffe_Couple_In_Love_600.jpg');"></div>
      <img class="error-image hidden" src="https://cdn3.iconfinder.com/data/icons/online-states/150/Snooze-512.png">
      <div class="start">
        <i class="fa fa-download" aria-hidden="true"></i>
        <div>Select a file or drag here</div>
        <div class="notimage hidden">Please select an image</div>
      </div>
      <div class="response hidden">
        <div class="message"></div>
      </div>
    </label>
  </form>
  <div class="filename"></div>
  <canvas></canvas>
</div>
<div class="checkalpha">
  <form class="file-upload-form uploader uploader--src">
    <input class="file-upload" type="file" name="fileUpload" accept="image/*" />
    <label for="file-upload" class="file-drag">
      <img class="file-image" src="" alt="Preview">
      <img class="error-image hidden" src="https://cdn3.iconfinder.com/data/icons/online-states/150/Snooze-512.png">
      <div class="start">
        <i class="fa fa-download" aria-hidden="true"></i>
        <div>Select a file or drag here</div>
        <div class="notimage hidden">Please select an image</div>
      </div>
      <div class="response hidden">
        <div class="message"></div>
      </div>
    </label>
  </form>
  <div class="filename"></div>
  <canvas></canvas>
</div>

null


共1个答案

匿名用户

如果我正确地理解了这个问题,那么你打算找出图像是什么。 让我们为此写一个函数:

function getImageLocation(element) {
    if (element.tagName.toLowerCase() === "img") {
        return element.src;
    }
    var rawSource = element.style["background-image"];
    //The raw value looks like url("somepath")
    //Let's extract somepath
    return rawSource.replace(`url("`, ``).replace(`url('`, ``).replace(`")`, ``).replace(`')`, ``);
}

此函数需要Javascript元素。 如果需要,可以将其转换为jQuery样式。