如何使用File API和Dropzone.js检测文件的大小

Mar*_*tin 6 javascript dropzone.js

使用Dropzone.js,我需要在添加文件时检测图像的尺寸,并将它们应用到其父.detailsdiv.以下代码代码可以工作并返回添加了图像宽度的警报.

myDropzone.on("addedfile", function(file, xhr) {
  var fr;
  fr = new FileReader;
  fr.onload = function() {
    var img;
    img = new Image;
    img.onload = function() {
      return alert(img.width);
    };
    return img.src = fr.result;
  };
  return fr.readAsDataURL(file);
});
Run Code Online (Sandbox Code Playgroud)

问题是我不知道如何将宽度分配给其父.details元素,该元素设置预览的预览宽度.

我尝试替换此代码的警报,但它没有做任何事情.

$(this).parent('.details').css('height',img.height);
Run Code Online (Sandbox Code Playgroud)

我有点迷失在如何将onload函数中的值与将其应用于其父类相关联.

eny*_*nyo 5

使用最新版本的 dropzone,您不必自己编写此代码。

只需读取生成缩略图时在对象上设置的file.width和属性即可。file.heightfile

问题是,为什么你的 CSS 不影响元素,是因为你没有指定单位,px在这种情况下。所以你的代码可以是:

myDropzone.on("thumbnail", function(file) {
  $(this.element).parent('.details').css('height', file.height + 'px');
});
Run Code Online (Sandbox Code Playgroud)

  • 这就是我如何设法接受仅大于 1024x768 的文件(我一直使用它进行隐写术,所以我只需要大约 786432 像素将数据加密到图像中..) `accept: function(file, done) { var Pixels = 0 ; var reader = new FileReader(); reader.onload = (函数(文件) { var image = new Image(); image.src = file.target.result; image.onload = function() { 像素 = this.width * this.height; if (像素 < 786432) { 完成("废话"); } else { 完成(); } }; }); reader.readAsDataURL(文件); }, ` (8认同)
  • 不是当我(可能还有问题的作者)需要它时。dropzone 不提供在“accept”和可能的“addedfile”上获取文件尺寸的方法 (2认同)
  • @nikans - 当触发“addedFile”和“accept”时,不会计算尺寸。它们是在触发“thumbnail”、“progress”和“success”之前计算的。 (2认同)