gpt4 book ai didi

javascript - 触发文件下载的正确方法?

转载 作者:太空狗 更新时间:2023-10-29 13:12:23 29 4
gpt4 key购买 nike

在 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;

最佳答案

没错,IE nor Edge 不支持下载属性(Edge 13+ 支持):http://caniuse.com/#feat=download

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

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

或新窗口:

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

两个限制:

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

关于javascript - 触发文件下载的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32207504/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com