![](/img/trans.png)
[英]How to determine the downloading file type before it actually starts downloading using javascript?
[英]Is it possible to get file type before downloading it through JavaScript?
我正在嘗試創建一個擴展,它將在通過popup下載之前告訴用戶文件類型。在下載之前,JavaScript中是否有任何方法來分析文件類型?
您可以通過在執行HEAD請求時檢查Content-type標頭來獲取文件類型。
那將不會下載內容。 例如,您可以使用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);
您可能還希望將錯誤處理添加到代碼中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.