LoginSignup
0
0

More than 3 years have passed since last update.

JavaScriptでPDFのファイルサイズを取得して表示させる方法

Last updated at Posted at 2021-02-28

実務で使う機会があったので、忘れないように投稿。

html
<a href="" class="js-pdfSize" target="_blank" data-filepath=""><p>PDFダウンロード<span class="file_size">0.0MB</span></p></a>
js
jQuery(function () {

jQuery.each(jQuery(".js-pdfSize"), function () {
  b(jQuery(this))
});

function b(d) {
  var h = "-";
  var g = d.data("filepath");
  if (!g) {
    d.find(".file_size").html(h);
    return
  }
  var e = g.split(".");
  if (e[e.length - 1].toLowerCase() !== "pdf") {
    d.find(".file_size").html(h);
    return
  }
  var f = $.ajax({
    type: "HEAD",
    url: g,
    dataType: "text"
  }).done(function () {
    var i = f.getResponseHeader("Content-Length");
    d.find(".file_size").html(c(i))
  }).fail(function () {
    d.find(".file_size").html(h)
  })
}

function c(d) {
  if (d < 1024) {
    return d + "B"
  } else {
    d = a(d)
  }
  if (d < 1024) {
    return d + "KB"
  } else {
    d = a(d)
  }
  if (d < 1024) {
    return d + "MB"
  } else {
    return a(d) + "GB"
  }
}

function a(d) {
  return (Math.ceil((d * 10) / 1024)) / 10
}
});

});
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0