【问题标题】:DropzoneJS: Preview selected image before upload in div as <img>DropzoneJS:在 div 中作为 <img> 上传之前预览所选图像
【发布时间】:2019-12-15 06:21:58
【问题描述】:

我目前正在寻找一种方法来显示选定的图像,然后通过 DropzoneJS 在 div 包装器中将其上传为&lt;img&gt; 元素。这里有人告诉我这是可能的,但我找不到方法。所以也许有人知道该怎么做?

jQuery(document).ready(function() {
  jQuery("#upload-image-dropzone").dropzone({
    url: "my-ajax-url",
    dictDefaultMessage: "Move files here to upload",
    autoProcessQueue: false,
    previewsContainer: !1,
    maxFilesize: 20,
    maxFiles: 1,
    uploadMultiple: !1,
    acceptedFiles: ".png, .jpg, .jpeg",
    init: function() {
      this.on("addedfile", function(file) {
        this.files.length > this.options.maxFiles && this.removeFile(this.files[0]);
      })
    },
    success: function() {}
  });
});
#upload-image-dropzone {
  width: 100%;
  height: 60px;
  border: 1px dotted #222222;
  border-radius: 3px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js" integrity="sha256-cs4thShDfjkqFGk5s2Lxj35sgSRr4MRcyccmi0WKqCM=" crossorigin="anonymous"></script>
<div id="upload-image-dropzone"></div>
<div id="image-preview-container"><img/></div>

【问题讨论】:

    标签: javascript jquery html css dropzone.js


    【解决方案1】:

    您可以使用FileReader API 预览图像,一旦在文件输入中被选中。

    请注意,对 IE 10/11 的支持是部分的,IE9 根本不支持 (ref)

    ** 在您的特定场景中,请将“importImage”函数放置在“ addedfile”侦听器中。 https://jsfiddle.net/yzm8v203/3/

    function importImage(input) {
      let fileReference = input.files && input.files[0];
      
      if(fileReference){
    		  var reader = new FileReader();
        
        reader.onload = (event) => {
    			document.getElementById('preview').src = event.target.result;
        }
        
        reader.readAsDataURL(fileReference); 
        
      }
    
    }
    
    document.getElementById('uploadInput').addEventListener('change', function(){ importImage(this) })
    <input type='file' id="uploadInput" />
    <img id="preview" src="" alt="Image preview" />

    【讨论】:

    • 首先,感谢您的回答!但是我上面的代码 sn-p 有可能吗?因为你在这里使用了一个输入,但我是一个 dropzone。
    • 在幕后,dropzone.js 使用文件输入,所以正如我在答案中提到的,在你的具体情况下,你需要在“addfile”中调用“importImage” “听众。看小提琴jsfiddle.net/yzm8v203/3
    • ...通过 DropzoneJS 上传之前的图像...但是好的,我会尝试的。感谢您的帮助:)
    • 哈现在我明白了,但应该是什么过程?你想怎么预览呢?就像拖动后应该有一个按钮可以提交上传?
    • 成功了。谢谢!
    猜你喜欢
    • 2016-07-23
    • 2011-05-26
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多