我正在尝试使用javascript / jquery获取通过api提供的mp3文件的文件大小。 当我在控制台中运行以下代码时:
function getFileSize(url, callback) {
var request = new XMLHttpRequest();
//get only header.
request.open("HEAD", url, true);
request.onreadystatechange = function() {
if (this.readyState == this.DONE) {
callback(parseInt(request.getResponseHeader("Content-Length")));
}
};
request.send();
}
//Example: Coldplay - Adventure of a Lifetime, 04:18 duration (280 in seconds)
getFileSize("https://datmusic.xyz/stream/nRPk:X3E3gB", function(sizeInBytes){
duration = 280; //seconds
bitrate = sizeInBytes / duration;
console.log("~" + bitrate + " kbps")
})
有时会返回正确的值
~36959.53214285714 kbps
但大部分时间都会返回
XMLHttpRequest cannot load https://datmusic.xyz/stream/nRPk:X3E3gB. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://butane.stereostance.com' is therefore not allowed access.
VM109:17 ~NaN kbps
即使只刷新相同的标签并重新运行代码也会产生不同的结果。如何获得一致的结果,最重要的是获取文件大小?
编辑: