javascript window.open 本地文件路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48212124/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:53:00  来源:igfitidea点击:

window.open for local file path

javascriptecmascript-5window.open

提问by Brian Ruchiadi

I would like to trigger download with window.open() function in javascript in local. The path should start with "/". I provide URL with / to start, however, it seems like window.open() function ignore the first /. Is there a way to make it read the / , so that i can trigger download?

我想在本地的javascript中使用window.open()函数触发下载。路径应以“/”开头。我提供带有 / 的 URL 开始,但是,window.open() 函数似乎忽略了第一个 /。有没有办法让它读取 / ,以便我可以触发下载?

回答by Quentin

A URL starting with a /is a relativeURL with an absolute path. It ignores the existing path on the URL, and calculates the new one starting from the end of the port (or hostname if there is no port, localhostin this case).

以 a 开头的URL 是具有绝对路径/相对URL 。它忽略 URL 上的现有路径,并从端口的末尾开始计算新路径(如果没有端口,则为主机名,在这种情况下)。localhost

If you want to make a request to a different URL scheme (in this case file:instead of http:) then you need to use an absoluteURL (i.e. state the new URL scheme explicitly).

如果您想向不同的 URL 方案(在这种情况下file:而不是http:)发出请求,那么您需要使用绝对URL(即明确说明新的 URL 方案)。

NB: Many browsers will block requests to file:scheme URLs triggered by pages which were not served using the file:scheme for security reasons.

注意:出于安全原因,许多浏览器会阻止对file:由未使用该file:方案提供服务的页面触发的方案 URL 的请求。

回答by Léo R.

Try use this :

尝试使用这个:

window.open('file:///D:/Examples/file2.extension')

It work for me with a local file

它对我有用本地文件

回答by Tajni

For security reasons browsers block opening local files using window.open().

出于安全原因,浏览器会阻止使用window.open().

In order to display local file you must urge user to manually choose file you want them to open. I know that is not the desirable solution but it is how can it work. One of implementation with FileReaderis in this answer: How to open a local disk file with JavaScript?

为了显示本地文件,您必须敦促用户手动选择您希望他们打开的文件。我知道这不是理想的解决方案,但它是如何工作的。FileReader的实现之一是在这个答案中:How to open a local disk file with JavaScript?