如何使用 Javascript/jQuery 从 FTP 服务器强制下载而不是打开 Chrome 中的 srt 文件?

How to force download instead of opening srt file in Chrome from an FTP server using Javascript/jQuery?

我必须从 FTP 服务器下载 srt 文件,我正在使用此代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $("a").bind('click', function () {
            var a = document.createElement("a");
            a.href = 'ftp://192.168.1.1/mytextfile.srt';
            a.download = 'mytextfile.srt';
            a.click();
        });
    });
</script>
<html>
    <a>Download</a>
</html>

问题是 Chrome 中的文件已打开,但 下载。我想当用户点击下载 link 来下载 srt 文件。如何强制 Chrome 下载文件?

我需要在 javascript/jQuery 而不是 php 中执行此操作。

您无法从 FTP 服务器操作 HTTP headers,FTP 仅提供数据。因此,您不能使用 download 属性或 Content-Disposition header。

这意味着由 Chrome 浏览器决定如何处理通过 FTP 切断的文件。我建议您从 HTTP 服务器提供文件,而不是使用 FTP.

之后,您可以将响应中的 Content-Disposition header 设置为 server-side 上的 attachment:

Content-Disposition: attachment; filename="filename.srt"

或使用HTML5锚点的download attribute,但要注意:

  • Although HTTP(s) URLs need to be in the same-origin, blob: URLs and data are allowed so that content generated by JavaScript can be downloaded.
  • If the HTTP header Content-Disposition: gives a different filename than this attribute, the HTTP header takes priority over this attribute.
  • If Content-Disposition: is set to inline, Firefox prioritizes Content-Disposition, like the filename case, while Chrome prioritizes the download attribute.