php - cakephp文件下载链接

标签 php cakephp

我遇到了两天多来一直试图解决的问题:我使用 cakephp 构建了一个网站,一切正常,但当我尝试实现存储文件的下载链接时,我遇到了困难在 APP_DIR/someFolder/someFile.zip 下。

如何设置下载链接到 someFolder 中的文件?我经常偶然发现“媒体 View ”,我尝试实现它们,但到目前为止我一直没有成功。

还有没有更简单的方法让文件可以下载?

最佳答案

媒体 View 自 2.3 版起已弃用。你应该使用 Sending files相反。

在你的 Controller 中检查这个最小的例子:

public function download($id) {
    $path = $this->YourModel->aMagicFunctionThatReturnsThePathToYourFile($id);
    $this->response->file($path, array(
        'download' => true,
        'name' => 'the name of the file as it should appear on the client\'s computer',
    ));
    return $this->response;
}

$this->response->file的第一个参数是相对于你的APP目录的。因此调用 $this->response->file('someFolder' . DS . 'someFile.zip') 将下载文件 APP/someFolder/someFile.zip

“发送文件”至少需要 CakePHP 2.0 版。还请考虑查看上面的 Cookbook 链接。


如果您运行的是旧版本的 CakePHP,您应该使用您在问题中已经提到的 Media Views。使用此代码并引用 Media Views (Cookbook) .

以下是旧版本的相同方法:

public function download($id) {
    $this->viewClass = 'Media';
    $path = $this->YourModel->aMagicFunctionThatReturnsThePathToYourFile($id);
    // in this example $path should hold the filename but a trailing slash
    $params = array(
        'id' => 'someFile.zip',
        'name' => 'the name of the file as it should appear on the client\'s computer',
        'download' => true,
        'extension' => 'zip',
        'path' => $path
    );
    $this->set($params);
}

关于php - cakephp文件下载链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15887953/

相关文章:

php - BLOB 下载截断为 1 MB 脚本适用于小于 1 MB 的文件

cakephp - CakePHP MVC Controller 可以返回图像吗?

php - CakePHP - 代码 $hasOne 的结果

php - 将子域重定向到包含 CakePHP 应用程序的主目录中的文件夹

php INSERT INTO 数据库变量名

php - 在 Laravel 中提供 PHP 图像资源作为响应

php - 在 PHP 中设置 SQLite3 PDO 驱动程序

php - 整洁地编写 MySQL 查询以提高可读性的推荐方法是什么?

php - 如何制作由 Google 索引为静态页面的 PHP/Cakephp 数据库驱动页面

mysql - 在 Phinx-Migration 中使用 "Point"-Datatype(在 CakePhp 中)