jQuery 带有文件名路径的 HTML5 文件 API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16710302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 File API with filename path
提问by Ashwin Hegde
I have following code to read file through HTML5 File API. I have uploaded the file via input=file element. Following is the code block.
我有以下代码可以通过 HTML5 File API 读取文件。我已经通过 input=file 元素上传了文件。以下是代码块。
<input type="file" id="files" name="file" />
<button id="readFile">Read File</button>
<output id="content"></output>
<script>
function readFile()
{
/* Get the reference of the inpout element. */
var files = document.getElementById('files').files;
console.log(files);
if (!files.length)
{
alert('Please select a file!');
return;
}
/* Reading the first file selected. You can process other files similarly in loop. */
var file = files[0];
/* Instantiate the File Reader object. */
var reader = new FileReader();
/* onLoad event is fired when the load completes. */
reader.onload = function(event) {
document.getElementById('content').textContent = event.target.result;
};
/* The readAsText method will read the file's data as a text string. By default the string is decoded as 'UTF-8'. */
reader.readAsText(file);
}
document.getElementById('readFile').addEventListener('click', function(event) {
readFile();
}, false);
</script>
What if I don't want to uploaded the file and provide filepath via input=type element to HTML5: File API to read the file and display it?
如果我不想上传文件并通过 input=type 元素向 HTML5: File API 提供文件路径以读取文件并显示它怎么办?
I know that the HTML5: File API don't take direct file path. Is there any solution ?
我知道 HTML5: File API 不采用直接文件路径。有什么解决办法吗?
采纳答案by Majid Kalkatechi
For Security reason, the browsers does not allow access to absolute path & file systems directly to Javascript. You can only get the file name by calling the 'val()' function in javascript and nothing more.
出于安全原因,浏览器不允许直接通过 Javascript 访问绝对路径和文件系统。您只能通过在 javascript 中调用 'val()' 函数来获取文件名,仅此而已。
So don't waste your time.
所以不要浪费你的时间。
回答by chaity
Latest version of IE return the complete absolute path of your file in the textbox. You may want to use: var filePath = document.getElementById("myFile").value; to get the absolute path
最新版本的 IE 在文本框中返回文件的完整绝对路径。您可能需要使用: var filePath = document.getElementById("myFile").value; 获取绝对路径
P.S. tried only on IE 11
PS 只在 IE 11 上试过