javascript - 使用 Javascript/PHP 的“另存为”框

标签 javascript php file

在我的网站上,我有一个 JavaScript 函数,它使用 PHP 函数在我的服务器上本地创建一个文件(与网站文件相同的目录)。该文件的名称只有这些 JavaScript 和 PHP 函数知道。 我想打开一个常规的“另存为”框以供用户下载该文件。 有没有一种方法可以使用 Javascript/PHP 以适用于 Firefox、Chrome 和 Explorer/Edge 的方式执行此操作? (只有Javascript/PHP知道文件名)

这是 PHP 示例:

file_put_contents($filename,$txt);

header('content-type: application/text');
header('content-disposition: attachment; filename=' . $filename);

readfile($filename);

最佳答案

在 Chrome 和 Firefox 中,它会自动保存,在 IE 中,会打开一个窗口,因此,如果用户默认情况下未更改其设置,则无论他们使用什么浏览器,他们都会看到保存对话框的位置。转到

https://support.google.com/chrome/answer/95574?hl=en-GB

了解更多信息。您可以使用 php 代码从服务器下载文件。

header('content-type: application/[type]');
header('content-disposition: attachment; filename=yourfile.file-extension');
readfile('yourfile.file-extension');

对于大文件,可以使用

function readfileChunked($filename, $retbytes=true){
 $chunksize = 1*(1024*1024);
 $buffer = '';
 $cnt = 0;
 $handle = fopen($filename, 'rb');

 if ($handle === false) {
     return false;
 }

 while (!feof($handle)) {
     $buffer = fread($handle, $chunksize);
     echo $buffer;
     ob_flush();
     flush();
     if ($retbytes) {
         $cnt += strlen($buffer);
     }
 }

 $status = fclose($handle);

 if ($retbytes && $status) {
     return $cnt; // return num. bytes delivered like readfile()  does.
 }

 return $status;
 }
header('Pragma: public');     // required
header('Expires: 0');     // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.$name.'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '. get_remote_size($url) );
header('Connection: close');
readfileChunked( $url );

关于javascript - 使用 Javascript/PHP 的“另存为”框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40238710/

相关文章:

javascript - window.open 在 Windows Phone 8 上返回 null

javascript - 图像轮播波动且未给出预期结果

javascript - 如何在Mongo中访问变量的值?

php - Supervisord 为 PHP 和 Gearman 添加多个进程

c - 如何知道哪个函数调用了另一个

javascript - 正则表达式 - 避免表达式中出现字符串

php - Laravel:使用 Memcache 而不是文件系统

php - MySQL时间间隔查询重载服务器

python - python 关联文件中的项目

linux - 基于第三个数字键的反向排序