gpt4 book ai didi

javascript - 尝试通过 PHP 通过 XML 请求下载图像文件

转载 作者:行者123 更新时间:2023-11-28 00:50:37 28 4
gpt4 key购买 nike

被这个问题困扰了一段时间。我正在尝试通过 javascript 和 PHP 强制下载文件。

如果我直接访问 PHP 页面,它可以工作,但我希望在不同页面上开始下载,但没有成功。

文件的 URL 取决于从 SELECT 项获取的值,但是这部分按预期工作,因此我将其排除在外。

Javascript

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", postUrl, true); //postUrl = http://www.example.com/downloadFile.php?url=http://www.example.com/files/test.eps

xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send();

PHP

$url = "http://www.example.com/files/test.eps";
$filesize= strlen(file_get_contents($url));

header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($url));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . $filesize);
readfile($url);

我一直在测试 GET 和 POST(不确定哪一个最好,请随时纠正我),但现在我正在尝试让 GET 工作。就像我说的,如果我直接访问“http://www.example.com/downloadFile.php ”,则会下载文件,如果我执行 console.log(xmlHttp.responseText) ,文件内容会写入控制台,但文件不会写入从其他页面发出请求时下载。

任何帮助将不胜感激。

最佳答案

结果我使用了@Vivasaayi 发布的链接,但我做了一些轻微的改动。我没有使用 Iframe,而是使用了常规的 a href。 PHP 文件未更改。

Javascript

var downloadLinkID = 'hiddenDownloadLink', downloadHref = document.getElementById(downloadLinkID);
if (downloadHref === null)
{
downloadHref = document.createElement('a');
downloadHref.id = downloadLinkID;
downloadHref.setAttribute('href', postUrl + params);
downloadHref.setAttribute('onclick', firefoxDownload(postUrl + params)); // FF/IE must have onclick event to make link clickable
downloadHref.click();

}

function firefoxDownload(url)
{
window.location.href = url; //Needed for FF/IE to force download of file

}

关于javascript - 尝试通过 PHP 通过 XML 请求下载图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26842804/

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