dougao2830 2010-07-09 11:09
浏览 26
已采纳

如何在不离开页面的情况下强制执行“另存为”对话框?

I have an anchor tag:

<a href="file.pdf">Download Me</a>

I would like for the user to click on it and then have a Save-As dialog box appear with a new filename I determine.

I found this(http://www.w3schools.com/php/func_http_header.asp):

header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in file.pdf
readfile("file.pdf");

I don't understand where to put those headers. At the top of the page? When I try to place those 3 lines directly above my link I receive the following errors:

Warning: Cannot modify header information - headers already sent by (output started at /home5/ideapale/public_html/amatorders_basic/admin/download.php:38) in /home5/ideapale/public_html/amatorders_basic/admin/download.php on line 118

I got the same error for both of the header lines I just added. Right after that, there are thousands lines of ASCII letters. How can I get the Save-As dialog box to appear using either jQuery or PHP(whatever is easier)?

  • 写回答

3条回答 默认 最新

  • douweng9427 2010-07-09 12:57
    关注

    Please be careful when using Stijn Van Bael's code, it opens you up to some serious security exploits.

    Try something like:

    --- download.php ---
    $allowed_files = array('file.pdf', 'otherfile.pdf');
    
    if (isset($_REQUEST['file']) && in_array($_REQUEST['file'], $allowed_files))
    {
      $filename = $_REQUEST['file'];
    
      header("Content-type:application/pdf");
      header("Content-Disposition:attachment;filename='$filename'");
    
      // The PDF source is in file.pdf
      readfile($filename);
    
      exit();
    }
    else
    {
      // error
    }
    
    
    --- linkpage.php ---
    <a href="download.php?file=file.pdf">Download PDF</a>
    <a href="download.php?file=otherfile.pdf">Download PDF</a>
    

    Probabaly a better way to do this is at the web server level (this can go in .htaccess) This will force all PDF's to be treated as a binary file (forcing the browser to download them) in and below the directory you put this in.

    <FilesMatch "\.(?i:pdf)$">
     Header set Content-Disposition attachment
     ForceType application/octet-stream
    </FilesMatch>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?