php - PHP 文件下载:PHP 正在 ajax 响应中发送文件数据,但文件未下载
问题描述
我有一个HTML
允许用户下载文件的页面,有一个下载按钮,我正在使用onClick
事件来ajax
调用php
提供文件数据的脚本。
问题是响应中收到了文件数据,但未下载文件。
我已经通过 ajax 请求帖子提到了这个 Php 文件下载,但没有解决我的问题
HTML
页
<button onClick="download()"> Download </button>
<script>
function download {
var url = "download"; //it is a code ignitor project hence it is just an action call.
var path ="<?php echo $data[0]->file_path . $data[0]->file_name; ?>";
$.post(url, {path: path}, function(result){
});
</script>
PHP script
public function download() {
$path = $this->input->post('path');
if(!file_exists($path)){
die('file not found');
} else {
header("Content-Disposition: attachment; filename=" . basename($path) . "");
header("Content-Length: " . filesize($path));
header("Content-Type: application/octet-stream;");
readfile($path);
}
}
谢谢。
解决方案
更改服务器功能,使其使用get
参数。然后使用脚本 URL 打开一个新窗口。
function download() {
var path ="<?php echo $data[0]->file_path . $data[0]->file_name; ?>";
var url = "download?path=" + encodeURIComponent(path); //it is a code ignitor project hence it is just an action call.
window.open(url);
});
public function download() {
$path = $this->input->get('path');
if(!file_exists($path)){
die('file not found');
} else {
header("Content-Disposition: attachment; filename=" . basename($path) . "");
header("Content-Length: " . filesize($path));
header("Content-Type: application/octet-stream;");
readfile($path);
}
}
推荐阅读
- javascript - 服务器端渲染中只能在浏览器中运行的包错误
- git - 用分支替换 git master (就像在 nuke master 中完全一样,只有分支,而不是一些单独的提交)
- javascript - React Native - 数组内对象内的数组状态更新问题
- mysql - 从表中选择多行并插入到不同的表中
- python - 我如何在 Ubuntu 中使用 pyenv 返回我的系统 python
- javascript - Vue - 是否可以在组件的计算属性中使用 Vuex getter?
- javascript - rm -rf 不显示任何错误但不删除任何文件 VS Code
- android - adb - 添加 PIN 但不安全启动的脚本
- java - 如何通过 HSSFWorkbook 设置图像大小
- apache-kafka - Kafka文件流连接和流API