如何根据上传的文件类型设置背景图片

问题描述

我正在尝试使输入文件预览。如果单击标签,则图像预览应设置为标签的背景图像。到目前为止,我可以使它工作。现在,如果上传文件是pdf(例如),我想将标签的背景图像设置为pdf徽标图像。

我有单独执行此操作的代码,但未与if语句一起执行

$("#boleto").on("change",function() {

// THIS IS FOR IMAGE PREVIEW

  var reader = new FileReader();
  reader.onload = function(e) {
    $("#previewboleto").css({
      "background-image": "url(" + e.target.result + ")","background-position": "center","background-size": "100%"
    });
  };
  reader.readAsDataURL(this.files[0]);
  
  //
  
  // THIS CODE SHOULD SET BACKGROUND TO A PDF logo IMG

  Object.values(this.files).forEach(function(file) {
    console.log(`Type: ${file.type}`);

    if (file.type == 'application/pdf') { //IF THE UPLOADED FILE IS A PDF...

      Object.values(this.files).forEach(function(file) {
        console.log(`Type: ${file.type}`);
        if (file.type == 'application/pdf') {
          $("#previewboleto").css({
            "background-image": 'url("https://www.google.com/url?sa=i&url=https%3A%2F%2Fes.wikipedia.org%2Fwiki%2FArchivo%3APDF_file_icon.svg&psig=AOvVaw0fAUI2NwxolUUCjOI_Gyxv&ust=1601173071562000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCIDTndTghewCFQAAAAAdAAAAABAQ")',"background-repeat": "no-repeat"
          });
        }
      })

    } else {

// IF UPLOADED FILE IS AN IMAGE...

    }

  });

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

.labelboleto,.labeldni {
  width: 100%;
  height: 190px;
  background-color: gray;
  Box-shadow: 0px 2px 11px rgba(0,0.0582113);
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="file" name="boleto" id="boleto" accept="image/*;capture=camera">
<label for="boleto" class="labelboleto" id="previewboleto"></label>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)