【问题标题】:Correct way to trigger file download?触发文件下载的正确方法?
【发布时间】:2015-08-25 15:00:56
【问题描述】:

在 public/templates/calendar.html 我有

<a href="" id="secret_download_button" style="display:none" download="">

在同一个文件中,我有一个按钮(下载 qr),我从 javascript 进行 ajax 调用,qr 在 /public/uploads/thumbs/qrcodes/'filename' 中创建 ajax 调用已完成,并调用以下函数,该函数位于

public/javascript/some.js

function (data) {
        $('#secret_download_button').attr('href',data.content);
        $('#secret_download_button').attr('download','somename');
        $('#secret_download_button').click();
    });

data.content = public/upload/thumbs/qrcodes/someqr.png(示例)

我需要使用相对路径,而不是绝对路径。我究竟做错了什么 ?我猜我设置的 href 路径错误。 同样从我在网上阅读的内容来看,IE 不支持此解决方案。是否有另一种更简单、更优雅的方法(我需要能够指定要下载的文件的名称)

编辑

最后在服务器端解决了。谢谢。对于其他有同样问题的人,我使用了这个:

            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($activity_name . '.png').'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($root . $path . $file_name));
            readfile($root . $path . $file_name);
            exit;

【问题讨论】:

  • 您的服务器端语言是什么?如果是c#,可以发出GET请求,返回FileResult,下载图片或文件。
  • 为什么'Pragma: public ?如果您打算像Cache-Control 一样使用它,它应该是Pragma: no-cachedeveloper.mozilla.org/en-US/docs/Web/HTTP/Headers/Pragma

标签: javascript html download


【解决方案1】:

你是对的,IE nor Edge不支持download属性(Edge 13+支持):http://caniuse.com/#feat=download

要获得跨浏览器解决方案,您必须在当前窗口中打开网址:

function (data) {
    window.location.href = data.content;
});

或新窗口:

function (data) {
    window.open(data.content);
});

两个限制:

  • 你不能在客户端设置文件名,你必须在服务器端设置它
  • 如果可以读取文件(如图片、pdf...),浏览器将不会下载文件,您必须使用“另存为”

【讨论】:

  • 服务器可以添加header“Content-Disposition:attachment”,它会一直被下载。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多