Get size of file requested via ajax

2019-01-11 11:34发布

Here's what I'm hoping to do:

I want to send an ajax request to a file (preferably with jQuery), and once the file has been loaded, determine the size of the requested file.

After a bit of googling, it's clear that I don't even have a good idea of the right question to ask to figure this out. Any help would be greatly appreciated.

3条回答
够拽才男人
2楼-- · 2019-01-11 11:50

You could make a HTTP HEAD request, and get a file size approximate by reading the Content-Length HTTP Header.

This kind of request is used to obtain meta-information about the URL implied by the request, without transferring any content of it in the response.

var xhr = $.ajax({
  type: "HEAD",
  url: "path/to/file.ext",
  success: function(msg){
    alert(xhr.getResponseHeader('Content-Length') + ' bytes');
  }
});
查看更多
相关推荐>>
3楼-- · 2019-01-11 11:50

You could create a server-side command that takes the path and name of the file, opens the file to get the length, and sends the size back to the client. How you do it would depend on what server-side language you're using. Is that the type of action you're looking for?

查看更多
Explosion°爆炸
4楼-- · 2019-01-11 11:57
var XHRObj = $.ajax({
    type:'HEAD',
    url:'/',
    success:function(data) {
        console.log( XHRObj.getResponseHeader('Content-Length') )
    }
})

You basically do a HEAD HTTP request and query the Content-Length, which returns X bytes.

查看更多
登录 后发表回答