Reputation: 31
I am trying to create a extension which will tell the user file type before downloading it via popup.Is there any method in JavaScript to analyse the file type before downloading it?
Upvotes: 1
Views: 643
Reputation: 1032
You can get the file type by checking for the Content-type header when performing a HEAD request.
That won't download the content. For example, you can use XMLHttpRequest:
getMimeType = url => {
const request = new XMLHttpRequest();
request.open('HEAD', url);
const promise = new Promise(resolve => {
request.onreadystatechange = () => {
if (request.readyState == request.DONE) {
resolve(
request
.getAllResponseHeaders()
.split('\n')
.find(header => header.toLowerCase().startsWith('content-type'))
.split(':')[1]
.trim(),
);
}
};
});
request.send();
return promise;
};
// Random ad on this web site, prints image/jpeg
getMimeType('https://tpc.googlesyndication.com/simgad/18296964107941472197').then(console.log);
You might want to add error handling to the code as well
Upvotes: 1