我需要在不检查扩展名的情况下从位于我的服务器上的 url 图像中找出文件类型,但我不确定如何在不将图像放入这样的“输入”中的情况下执行此操作:
<input type="file" id="upload_file" accept="image/*|audio/*|video/*"/>
<input type="submit" onclick="sumbit()"/>
<script type="text/javascript">
function sumbit(){
var file_Element = document.getElementById("upload_file")
alert(file_Element.files[0].type);
//alert: image/png
}
<script>
我知道“.type”只适用于文件对象,所以我如何将 url 图像转换为像谷歌 Logo 图像这样的对象:https://www.google.ca/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png . 我需要使用 ajax/flilereader 吗?如果是,怎么办?
最佳答案
假设您的 Content-Type
HTTP header 是准确的,您可以通过创建 HEAD
请求来避免下载整个文件只是为了检查类型。假设您不需要整个文件来做其他事情,这可能是一个更快的操作,尤其是对于大文件。
工作示例(XHR):
var url = 'https://raw.githubusercontent.com/unikong/unikong.github.io/master/img/unikong/heart.png';
var xhr = new XMLHttpRequest();
xhr.open('HEAD', url, true);
xhr.onload = function() {
var contentType = xhr.getResponseHeader('Content-Type');
console.log(contentType);
};
xhr.send();
工作示例(获取):
(async () => {
var url = 'https://raw.githubusercontent.com/unikong/unikong.github.io/master/img/unikong/heart.png';
const reponse = await fetch(url, {
method: 'HEAD'
});
console.log(reponse.headers.get('Content-Type'));
})();
或者,您可以通过在 AJAX 请求对象加载整个主体之前调用 abort
来使用常规 GET
请求获得类似的结果(在任何最近的浏览器中)无论如何)。
替代工作示例:
var url = 'https://raw.githubusercontent.com/unikong/unikong.github.io/master/img/unikong/heart.png';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
// Wait for header to become available.
var contentType = xhr.getResponseHeader('Content-Type');
if (contentType) {
// Stop downloading, the headers are all we need.
xhr.abort();
console.log(contentType);
}
};
xhr.send();
关于javascript - 从 URL 获取文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38679681/