我需要从服务器上的 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>
Run Code Online (Sandbox Code Playgroud)
我知道“.type”仅适用于文件对象,那么如何将 url 图像转换为像 google 徽标图像这样的对象: https: //www.google.ca/images/branding/googlelogo/1x/ googlelogo_color_272x92dp.png。我需要使用 ajax/flilereader 吗?如果是这样,怎么办?
假设您的Content-TypeHTTP 标头准确,您可以通过创建请求来避免仅仅为了检查类型而下载整个文件HEAD。假设您不需要整个文件来做其他事情,这可能是一个更快的操作,特别是对于大文件。
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();Run Code Online (Sandbox Code Playgroud)
(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'));
})();Run Code Online (Sandbox Code Playgroud)
或者,您可以通过在加载整个正文之前调用 AJAX 请求对象(无论如何在任何远程最近的浏览器中)来使用常规GET请求获得类似的结果。abort
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();Run Code Online (Sandbox Code Playgroud)