【问题标题】:Download a remote file and rename the file- & filetype on client-side下载远程文件并在客户端重命名文件和文件类型
【发布时间】:2014-05-23 20:08:03
【问题描述】:

我正在开发一个项目,在该项目中,客户端应该从远程 URL 开始下载。

我目前让它与 cURL 一起使用,但问题是它下载到服务器,而不是客户端的浏览器上(询问保存位置)。

网址如下所示:

http://r13---sn-5hn7snee.googlevideo.com/videoplayback?expire=138181&mv=u&ipbits=0&clen=7511717&fexp=929447,913430,930802,916612,902546,937417,913434,936916,934022,936921,936923&ms=au&mt=1396164&itag=247&key=yt5&source=youtube&ip=2a00:7143:100:1:225:90ff:fe52:b3ad&sparams=clen,dur,gir,id,ip,ipbits,itag,lmt,source,upn,expire&signature=DBDCE9EFFC094C0FC653610C8FAAF367EA942CC4C6EF3971A186C&upn=0JQJ6yqyYPo&sver=3&gir=yes&lmt=13960601932&dur=130.133&id=17f0fd8b&size=1280x720,type=video/mp4

仅从 URL 下载时,文件名将是“videoplayback”,没有任何文件扩展名。所以我需要有一个自定义文件名和 .mp4 作为文件类型。 (适用于下面的 cURL 代码),但它写入服务器而不是客户端下载。

function download($file_source, $file_target) {
$rh = fopen($file_source, 'rb');
$wh = fopen($file_target, 'w+b');
if (!$rh || !$wh) {
    return false;
}

while (!feof($rh)) {
    if (fwrite($wh, fread($rh, 4096)) === FALSE) {
        return false;
    }
    echo ' ';
    flush();
}

fclose($rh);
fclose($wh);

return true;
}

$result = download('http://r13---sn-5hn7snee.googlevideo.com/videoplayback?expire=138181&mv=u&ipbits=0&clen=7511717&fexp=929447,913430,930802,916612,902546,937417,913434,936916,934022,936921,936923&ms=au&mt=1396164&itag=247&key=yt5&source=youtube&ip=2a00:7143:100:1:225:90ff:fe52:b3ad&sparams=clen,dur,gir,id,ip,ipbits,itag,lmt,source,upn,expire&signature=DBDCE9EFFC094C0FC653610C8FAAF367EA942CC4C6EF3971A186C&upn=0JQJ6yqyYPo&sver=3&gir=yes&lmt=13960601932&dur=130.133&id=17f0fd8b&size=1280x720,type=video/mp4');

if (!$result)
     throw new Exception('Download error...');

所以我的问题是如何将其转换为重命名文件并将扩展名更改为 mp4,然后在客户端下载文件。

谢谢

【问题讨论】:

    标签: php file download rename


    【解决方案1】:

    首先将正确的标头输出到客户端,以便它知道如何处理文件,然后回显文件内容。所以试试这个方法:

    <?php
    // ... fetch the file using CURL and store it (in memory or on file system) ...
    
    // Set the content type
    header('Content-type: application/pdf');
    
    // It will be called downloaded.pdf
    header('Content-Disposition: attachment; filename="downloaded.pdf"');
    
    // ... echo/output the file contents to the browser...
    ?>
    

    查看 PHP 文档中的“Example #1 Download dialog”。

    另外,您提到您正在使用 CURL,我在您的代码中的任何地方都没有看到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多