Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

javascript - 如何使用JavaScript打开本地磁盘文件?(How to open a local disk file with JavaScript?)

I tried to open file with

(我试图用打开文件)

window.open("file:///D:/Hello.txt");

The browser does not allow opening a local file this way, probably for security reasons.

(浏览器不允许以这种方式打开本地文件,可能出于安全原因。)

I want to use the file's data in the client side.

(我想在客户端使用文件的数据。)

How can I read local file in JavaScript?

(如何在JavaScript中读取本地文件?)

  ask by Joval translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's an example using FileReader :

(这是使用FileReader的示例:)

 function readSingleFile(e) { var file = e.target.files[0]; if (!file) { return; } var reader = new FileReader(); reader.onload = function(e) { var contents = e.target.result; displayContents(contents); }; reader.readAsText(file); } function displayContents(contents) { var element = document.getElementById('file-content'); element.textContent = contents; } document.getElementById('file-input') .addEventListener('change', readSingleFile, false); 
 <input type="file" id="file-input" /> <h3>Contents of the file:</h3> <pre id="file-content"></pre> 


Specs(眼镜)

http://dev.w3.org/2006/webapi/FileAPI/

(http://dev.w3.org/2006/webapi/FileAPI/)

Browser compatibility(浏览器兼容性)

  • IE 10+

    (IE 10以上)

  • Firefox 3.6+

    (Firefox 3.6以上版本)

  • Chrome 13+

    (铬13+)

  • Safari 6.1+

    (Safari 6.1+)

http://caniuse.com/#feat=fileapi

(http://caniuse.com/#feat=fileapi)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...