0

I want to show div with an image, it's name, it's size and it's download link with jquery.

for that, I have made below code

var image = 'image/example.png'
$('#download').attr("href", result2); 
$('.image').attr("src", result2); 
var name = result2.replace('image/', ''); 
$('.name').text(name);
$('.filename').css('display','block');
<div class="filename" style="display: none;">
    <img src="" class="image" width="100PX" height="100PX">
    <b class="name">example.png</b>             
    <span class="size"></span>
    <a href="" download="" id="download" class="btn" style="">DOWNLOAD</a>
</div>

and my image is

Image

everything is working fine except image size I don't know how can I get image size because when I was searching to get image size with it's MB, KB or in bytes with jquery it shows me a result in this formate $("#selector")[0].files[0].size but in my case, there is no files[0] is available so how can I find image size?

Tân
  • 1
  • 15
  • 56
  • 102
  • Does this answer your question? [Determining image file size + dimensions via Javascript?](https://stackoverflow.com/questions/1310378/determining-image-file-size-dimensions-via-javascript) – Hitesh Tripathi Dec 28 '19 at 04:31

1 Answers1

2

You can use fetch to get the reponse size. Since you make a request with an image path, the response size will points to the image size.

fetch($('img').prop('src')).then(function (response) {
    console.log('size:', response.headers.get("content-length"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<img src="https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" class="image" width="100PX" height="100PX" width="150" height="100">

Another way to get the image width/height is: Using Image class:

var image = new Image();

image.onload = function () {
  console.log('width:', this.width);
  console.log('height:', this.height);
  
  console.log('more information about this image:');
  console.dir(this);
};

image.src = $('img').prop('src');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<img src="https://images.unsplash.com/photo-1474511320723-9a56873867b5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" class="image" width="100PX" height="100PX" width="150" height="100">
Tân
  • 1
  • 15
  • 56
  • 102
  • thank you for your reply but as I mention in code I am mading image src dynamically so how can I use your code? –  Dec 28 '19 at 05:50
  • 1
    @MNJ Sure, whenever you have the path, you can use it with `fetch` and `Image`. In this example, I just show you how we can use it. – Tân Dec 28 '19 at 05:52