用ajax和php下载文件 - readfile无法正常工作

时间:2021-07-17 09:50:19

I want to save a value to a txt-file and download it to the user.

我想将值保存到txt文件并将其下载给用户。

Right now, the value is being printed into the txt-file correctly, but the readfile function is not triggered, thus no downloading begins.

现在,正确地将值打印到txt文件中,但不会触发readfile函数,因此不会开始下载。

The php, this code is located on the same page as the ajax call.

php,这段代码与ajax调用位于同一页面。

<?php 
if (isset($_POST['data']))
{
$handle = fopen("file.txt", "w");
fwrite($handle, $_POST['data']);
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');    
exit;   

}

?>

The javascript, there is no url because the data is to be sent to the current page.

javascript,没有url,因为数据将被发送到当前页面。

 function exportColors() {        
    var exportData = this.dataset.id;

    $.ajax({
            type: "POST",
            data: {data: exportData},
            success: function (data) {
               console.log(data);   
            }   
        });


}

4 个解决方案

#1


1  

You need to separate the functionality, that is, post the data to PHP first, save the content of the text file and then, in a second request, let the user download the file. So one (skeleton) approach would be:

您需要分离功能,即首先将数据发布到PHP,保存文本文件的内容,然后在第二个请求中让用户下载文件。所以一个(骨架)方法是:

JS File:

JS档案:

function exportColors() {        
    var exportData = this.dataset.id;

    $.ajax({
        type: "POST",
        data: {data: exportData},
        success: function (data) {
            // redirect or print out a link
        }   
    });

}

}

PHP File for the first request (saving the content):

第一个请求的PHP文件(保存内容):

<?php 
if (isset($_POST['data'])) {
    $handle = fopen("file.txt", "w");
    fwrite($handle, $_POST['data']);
    fclose($handle);
    // give back some unique id or the unique filepath
}
?>

PHP File for the second request (be it through clicking on a link or after having been redirected):

用于第二个请求的PHP文件(通过单击链接或重定向后):

// essentially everything that outputs your file
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');    
exit;   

Comments: Either give back a unique filepath or via a handle through a database (more secure, but more complex as well). Besides, why should the user download the unchanged data he has formerly submitted? Is there more to it than meets the eye?

注释:通过数据库返回一个唯一的文件路径或通过句柄(更安全,但也更复杂)。此外,为什么用户应该下载他之前提交的未更改数据?还有更多的东西比满足眼睛吗?

#2


0  

Ok I'm going out on a limb so take this with a grain of salt.

好吧,我出去了,所以带上一粒盐。

You said this request is going to the current page? Does that mean you've excluded (for the sake of brevity) HTML content from the PHP file you're showing us? If you have ANY content above your opening <?php tag, then any call to header will fail with an error (because headers must come before the body of a request). This would cause the script to terminate and prevent the readfile line from ever being reached.

你说这个请求会转到当前页面吗?这是否意味着您已经从您向我们展示的PHP文件中排除(为了简洁起见)HTML内容?如果您的开头<?php标记上方有任何内容,则对标题的任何调用都将失败并显示错误(因为标题必须位于请求正文之前)。这将导致脚本终止并阻止读取readfile行。

Are your headers being sent? Do you see anything in the error log? If the answers to these are yes and no respectively then I'm wrong and you can ignore this.

你的标题是否被发送?你在错误日志中看到了什么吗?如果这些答案分别为是和否,那么我错了,你可以忽略这一点。

#3


0  

Due to security reasons, ajax won't be able to download/save the file to the client's system because of java-script constraints.

由于安全原因,由于java脚本限制,ajax将无法将文件下载/保存到客户端系统。

Instead you can use

相反,你可以使用

jquery.fileDownload.js

Please have a look at http://jqueryfiledownload.apphb.com/

请看http://jqueryfiledownload.apphb.com/

Hope this helps.

希望这可以帮助。

#4


0  

you can't

你不能

beacuse javascript is not able to write on user file system.

beacuse javascript无法在用户文件系统上写入。

see answer

看到答案

Download a file by jQuery.Ajax

通过jQuery.Ajax下载文件

explain problem very well

很好地解释问题

#1


1  

You need to separate the functionality, that is, post the data to PHP first, save the content of the text file and then, in a second request, let the user download the file. So one (skeleton) approach would be:

您需要分离功能,即首先将数据发布到PHP,保存文本文件的内容,然后在第二个请求中让用户下载文件。所以一个(骨架)方法是:

JS File:

JS档案:

function exportColors() {        
    var exportData = this.dataset.id;

    $.ajax({
        type: "POST",
        data: {data: exportData},
        success: function (data) {
            // redirect or print out a link
        }   
    });

}

}

PHP File for the first request (saving the content):

第一个请求的PHP文件(保存内容):

<?php 
if (isset($_POST['data'])) {
    $handle = fopen("file.txt", "w");
    fwrite($handle, $_POST['data']);
    fclose($handle);
    // give back some unique id or the unique filepath
}
?>

PHP File for the second request (be it through clicking on a link or after having been redirected):

用于第二个请求的PHP文件(通过单击链接或重定向后):

// essentially everything that outputs your file
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');    
exit;   

Comments: Either give back a unique filepath or via a handle through a database (more secure, but more complex as well). Besides, why should the user download the unchanged data he has formerly submitted? Is there more to it than meets the eye?

注释:通过数据库返回一个唯一的文件路径或通过句柄(更安全,但也更复杂)。此外,为什么用户应该下载他之前提交的未更改数据?还有更多的东西比满足眼睛吗?

#2


0  

Ok I'm going out on a limb so take this with a grain of salt.

好吧,我出去了,所以带上一粒盐。

You said this request is going to the current page? Does that mean you've excluded (for the sake of brevity) HTML content from the PHP file you're showing us? If you have ANY content above your opening <?php tag, then any call to header will fail with an error (because headers must come before the body of a request). This would cause the script to terminate and prevent the readfile line from ever being reached.

你说这个请求会转到当前页面吗?这是否意味着您已经从您向我们展示的PHP文件中排除(为了简洁起见)HTML内容?如果您的开头<?php标记上方有任何内容,则对标题的任何调用都将失败并显示错误(因为标题必须位于请求正文之前)。这将导致脚本终止并阻止读取readfile行。

Are your headers being sent? Do you see anything in the error log? If the answers to these are yes and no respectively then I'm wrong and you can ignore this.

你的标题是否被发送?你在错误日志中看到了什么吗?如果这些答案分别为是和否,那么我错了,你可以忽略这一点。

#3


0  

Due to security reasons, ajax won't be able to download/save the file to the client's system because of java-script constraints.

由于安全原因,由于java脚本限制,ajax将无法将文件下载/保存到客户端系统。

Instead you can use

相反,你可以使用

jquery.fileDownload.js

Please have a look at http://jqueryfiledownload.apphb.com/

请看http://jqueryfiledownload.apphb.com/

Hope this helps.

希望这可以帮助。

#4


0  

you can't

你不能

beacuse javascript is not able to write on user file system.

beacuse javascript无法在用户文件系统上写入。

see answer

看到答案

Download a file by jQuery.Ajax

通过jQuery.Ajax下载文件

explain problem very well

很好地解释问题