作为附件发送文件到浏览器 [英] Sending file to a browser as attachment

查看:185
本文介绍了作为附件发送文件到浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/ b>从另一台没有下载到服务器的服务器:

  header('Location:http:// thirdparty。 COM / file.ext'); 

没有在本地下载文件,您在外部服务器上没有授权,所以您必须告诉浏览器该怎么做,因此重定向头,它会告诉服务器直接去提供的URL,从而加载下载。



从你的服务器,你会:

  if(file_exists($ file))
{
if(false!==($ handler = fopen($ file,'r')))
{
header('Content-Description:File Transfer');
header('Content-Type:application / octet-stream');
header('Content-Disposition:attachment; filename ='。basename($ file));
header('Content-Transfer-Encoding:binary');
header('Expires:0');
header('Cache-Control:must-revalidate,post-check = 0,pre-check = 0');
header('Pragma:public');
header('Content-Length:'。filesize($ file)); //删除

//发送块内容
while(false!==($ chunk = fread($ handler,4096)))
{
echo $ chunk;
}
}
exit;
}
echo< h1>内容错误< / h1>< p>档案不存在!< / p>」;

取自另一个问题我有回答


How to send a file to the browser as attachment if the meant file resides on a 3rd party server (without prior downloading or streaming)?

解决方案

From another server without downloading to your server:

header('Location: http://thirdparty.com/file.ext');

Without downloading the file locally you have no authorization in the external server, so you have to tell the browser what to do, thus the redirect header, it will tell the server to go directly to the url provided, thus loading the download.

From your server you would do:

if (file_exists($file))
{
    if(false !== ($handler = fopen($file, 'r')))
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file)); //Remove

        //Send the content in chunks
        while(false !== ($chunk = fread($handler,4096)))
        {
            echo $chunk;
        }
    }
    exit;
}
echo "<h1>Content error</h1><p>The file does not exist!</p>";

Taken from another question I have answered

这篇关于作为附件发送文件到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆