简体   繁体   English

jQuery / JavaScript下载文件在Chrome上不起作用

[英]jQuery / javascript download file doesn't work on Chrome

I have a jQuery script in which I want to download a file which is located on some server after the user clicks on the link. 我有一个jQuery脚本,在用户单击链接后,我想在其中下载文件,该文件位于某些服务器上。 On IE11 this works alright, as I simply make a call to: 在IE11上,此方法可以正常运行,因为我只是打电话给:

window.open('file:///MyServer0001/SomeFolder/Tmp/ToiletFlush.log'

I know that for security reasons, Chrome doesn't allow to use the protocol file:/// . 我知道出于安全原因,Chrome不允许使用协议文件:///。 It is interesting because if I write myself this URL on the address bar he will show the file, however if I make a call for window.open() he just opens me a new empty window. 有趣的是,如果我在地址栏上写这个URL,他将显示文件,但是,如果我调用window.open(),他只会为我打开一个新的空窗口。 Also, removing the file:/// , doesn't do anything on Chrome, it says that the page is not available 另外,删除file:///,在Chrome上不执行任何操作,表示该页面不可用

So right now I don't know how to make this work on chromium. 所以现在我不知道如何在铬上进行这项工作。 I thought I could make a workaround by calling the controller function through a POST/GET , return a FileResult and download the file. 我以为可以通过POST / GET调用控制器函数,返回FileResult并下载文件来解决。 This definitely works but I would like to know a simple way to do this directly only using jQuery/JavaScript. 这绝对可行,但是我想知道一种仅使用jQuery / JavaScript直接执行此操作的简单方法。

Any Idea? 任何想法?

Try ASP.NET MVC FileResult: 尝试使用ASP.NET MVC FileResult:

View: 视图:

<a href='@Url.Action('GetFile','Home')">Download File</a>

In Home Controller: 在家庭控制器中:

public FileResult GetFile()
{
//Read file content into variable.
string content=File.ReadAllText("filepath");
byte[] byteArray = Encoding.ASCII.GetBytes(content);
return File(byteArray, System.Net.Mime.MediaTypeNames.Text.Plain, "ToiletFlush.log");
}

Try this, 尝试这个,

On Windows: 在Windows上:
1. Find the local URL of your Chrome Install 1.找到您的Chrome安装程序的本地URL
2. From the Command Line launch Chrome w/ '–allow-file-access-from-files' prepended to it: 2.从命令行启动带有w-“-allow-file-access-from-files”的Chrome浏览器:

–allow-file-access-from-files C://...

On OSX, just type this in Terminal: 在OSX上,只需在终端中输入以下内容:

open /Applications/Google\ Chrome.app --args --allow-file-access-from-files

Using Google Chrome Canary is also possible:

open /Applications/Google\ Chrome\ Canary.app --args --allow-file-access-from-files

Or... You'll need to run your application on a local server. 或者...您需要在本地服务器上运行应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM