简体   繁体   English

filereader文件格式无法识别json和geojson

[英]filereader file format not recongnising json and geojson

I'm using filereader in Angular 2. I know that the file format can be accessed through: 我在Angular 2中使用filereader。我知道可以通过以下方式访问文件格式:

 file.type

when I load for example txt, the type is: text/plain. 当我加载例如txt时,类型为:文本/纯文本。 But when I load a json or geojson the returned value is empty. 但是,当我加载json或geojson时,返回值为空。

is there any reliable way to access to the types when its json, or geojson ? json或geojson时,是否有任何可靠的方法来访问类型?

The only reliable way to know if it is json or not would be to test the contents. 知道它是否为json的唯一可靠方法是测试内容。 Meaning run it through JSON.parse() . 意思是通过JSON.parse()运行它。 If it throws an exception out it isn't json (or is malformed json). 如果抛出异常,则它不是json(或者是格式错误的json)。

try {
  JSON.parse(fileContents);
} catch(e){
  console.log("Not a json file or file containing malformed json");
}

Mime types aren't stored as some piece of data inside files. Mime类型不会作为数据存储在文件中。 It is usually determined by extension, magic number (binary header), etc. And depending on implementation, the browser is more than likely just going to look at the extension and use some lookup table. 它通常由扩展名,幻数(二进制标头)等决定。根据实现的不同,浏览器很有可能只是查看扩展名并使用一些查找表。 It would seem the browser you used did not have one set for a .json file 您使用的浏览器似乎没有用于.json文件的一套

For instance loading a .json file in the below demo in Chrome will show application/json . 例如,在下面的Chrome演示中加载.json文件将显示application/json Changing it to .txt will make it see it as text/plain . 将其更改为.txt将使其显示为text/plain Changing it to some other extension will change it yet again. 将其更改为其他扩展名将再次对其进行更改。

 document.querySelector('input').addEventListener('change',function (){ document.body.insertAdjacentHTML('beforeend',this.files[0].type+"<br>"); }); 
 <input type="file" /><br> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM