为了账号安全,请及时绑定邮箱和手机立即绑定

有什么方法可以让 javascript 读取具有自定义扩展名的文件?

有什么方法可以让 javascript 读取具有自定义扩展名的文件?

德玛西亚99 2022-01-07 13:16:43
让我们考虑一个自定义扩展.cst,我们有一个 JavaScript 函数CSTReader()专门设计用于读取.cst文件。这是一个例子:文件.cst:I am a cst file. I have data in me such that I am readable by javascript.index.js: document.write("Reqd Output : " +  CSTReader("files.cst") );输出 :Reqd Output : I am a cst file. I have data in me such that I am readable by javascript.那么,可以制作CSTReader()吗?或者在 javascript 中是不可能的?如果没有,有什么替代方法吗?还是只是浪费时间?提前致谢
查看完整描述

1 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

您可以使用FileReader对象来执行此操作。它也适用于自定义扩展。查看https://developer.mozilla.org/fr/docs/Web/API/FileReader以获取文档。


如果您的文件包含纯文本,则可以使用该readAsText方法。


在您的示例中,您可以执行以下操作:


<input type="file" onchange="readFile"/> // put your file here

<script>


function readFile(e) {

  let file = e.target.files[0] // get the file


  let fileReader = new FileReader(); // instanciate Filereader

  fileReader.onloadend = function () { // bind your function to the onloadend method. It will be executed once the file is read.

    console.log(filereader.result);

    // do whatever you want with the content

  }; 

  fileReader.readAsText(file); // read the file, whatever the extension is.

}

</script>


查看完整回答
反对 回复 2022-01-07
  • 1 回答
  • 0 关注
  • 177 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号