我正在使用angular在控制器中使用以下代码在点击时发出POST请求...
var request = $http({
method: "post",
url: "../submit.php",
data: {
templateData: $scope.template
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
我将数据发送到一个名为php的文件submit.php
,一切正常,submit.php
接收数据。接下来我要处理的数据是将其写入文件...
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$contentFile = fopen("file.txt", "w");
fwrite($contentFile, $template);
fclose($contentFile);
这似乎有效,我没有收到错误。但是现在,我要发生的下一件事是将文件下载到浏览器。该代码应该可以工作,但是由于某些原因它不能下载到浏览器中。
header('Pragma: anytextexeptno-cache', true);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"file.txt\"");
完整代码
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$template = "";
foreach ($request as $data) {
foreach ($data as $sub) {
for ($i = 0; $i < count($sub); $i++) {
$template .= $sub[$i];
}
}
}
$contentFile = fopen("file.txt", "w");
fwrite($contentFile, $template);
fclose($contentFile);
header('Pragma: anytextexeptno-cache', true);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"file.txt\"");
?>
您唯一错过的是实际输出“文件”。
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$template = "";
foreach ($request as $data) {
foreach ($data as $sub) {
for ($i = 0; $i < count($sub); $i++) {
$template .= $sub[$i];
}
}
}
header('Pragma: anytextexeptno-cache', true);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"file.txt\"");
// here's the thing:
echo $template;
?>
这仅适用于文本/纯文本。
您不需要先将内容保存到文件中。
注意
您永远不能强制浏览器“下载”文件。某些浏览器可能会决定显示该文件。文件为“陌生人”时,将更有可能提示用户下载。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句