如何从javascript下载文件 [英] How to download file from javascript

查看:169
本文介绍了如何从javascript下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让我的下载功能弹出文件下载,当我点击链接时,它将文件的二进制文件输出到div,我怎么能这样,当我点击链接,它会否要求我下载?我知道我可以使用查询字符串和在PHP中使用头文件,但是我可以用类似的方式用ajax / javascript做它吗?谢谢,这是我试过的:

 < html> 
< head>
< script>
函数下载(plan_name)
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
}

xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4&& xmlhttp.status == 200)
{
var resp = xmlhttp.responseText;
document.getElementById(txtHint)。innerHTML = resp;


//如何在save-as对话框中显示test.zip?
}
}

xmlhttp.open(GET,fetcher.php?file = / raid0 / data / naswebsite / Projects / Projects / 07-003_Dawson_Mine / \\ Plans / Dawson_Sth_1211_AMG_700.zip);
xmlhttp.send();
}

< / script>
< / head>
< body>

< a href =#onClick =Download();>测试下载< / a>
< div id =txtHint>< / div>

< / body>
< / html>


解决方案

无法从AJAX下载文件请求。

相反,您可以将隐藏的< iframe> 中的URL加载。


I'm trying to make my Download function popup with the file to download, it is outputting the binary of the file to the div when i click the link, how can i make it so that when i click the link, it will instead ask me to download it? I know i can do it with querystring and using headers in php, but can i do it with ajax/javascript in a similar way? thanks, here's what i tried:

<html>
<head>
<script>
function Download(plan_name)
{
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            var resp = xmlhttp.responseText;
            document.getElementById("txtHint").innerHTML=resp;


            //HOW TO SHOW test.zip in a save-as dialog?
        }
    }

    xmlhttp.open("GET","fetcher.php?file=/raid0/data/naswebsite/Projects/Projects/07-003_Dawson_Mine/Flight\ Plans/Dawson_Sth_1211_AMG_700.zip");
    xmlhttp.send();
}

</script>
</head>
<body>

<a href="#" onClick="Download();">Test Download</a>
<div id="txtHint"></div>

</body>
</html>

解决方案

It is not possible to download a file from an AJAX request.
Instead, you can load the URL in a hidden <iframe>.

这篇关于如何从javascript下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆