[英]How to check whether a JSON File is selected in javascript?
How to check whether a JSON File is selected from the browser using match()
function in javascript.如何使用 JavaScript 中的match()
函数检查是否从浏览器中选择了 JSON 文件。
The below code snippet is used to check for image files:下面的代码片段用于检查图像文件:
<script>
var f=evt.target.files[0];
// Only process image files.
if (!f.type.match('image.*')) {
alert('Please select Image Files only!');
}
</script>
I want the same for JSON files.我想要同样的 JSON 文件。
Here's the answer, 8 years later:这是 8 年后的答案:
document.querySelector('input').onchange = function ({ target: { files: [file] } }) { if (file.type != 'application/json') { alert('Please select JSON files only!'); this.value = ''; return; } // for displaying the contents of the file const reader = new FileReader(); reader.onload = ({ target: { result } }) => console.log(result); reader.readAsText(file); };
<input type='file'/>
Actually, this only considers a file valid if it has the .json
extension, and would consider files as invalid if they had valid JSON
content but the wrong extension.实际上,这仅在文件具有.json
扩展名时才认为文件有效,如果文件具有有效的JSON
内容但扩展名错误,则将文件视为无效。 It would also be fooled by files with invalid JSON
but the correct extension.它也会被具有无效JSON
但正确扩展名的文件所愚弄。
The most reliable way to validate a JSON
file, if you must do this client-side, is calling JSON.parse
on the contents and checking if it throws an error:如果您必须在客户端执行此操作,验证JSON
文件的最可靠方法是对内容调用JSON.parse
并检查它是否抛出错误:
const validateJSON = data => { try { JSON.parse(data); } catch { return false; } return true; } document.querySelector('input').onchange = function ({ target: { files: [file] } }) { const reader = new FileReader(); reader.onload = ({ target: { result } }) => { if (!validateJSON(result)) { alert('Please select JSON files only!'); this.value = ''; return; } // display the contents of the file console.log(result); } reader.readAsText(file); };
<input type='file' />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.