droos02800 2013-04-08 20:05
浏览 88
已采纳

cakephp文件下载链接

I've encountered a problem I'm trying to solve for more than two days now: I've built a Website using cakephp and everything is working just fine but I got stuck when I tried to implement download links to files stored under APP_DIR/someFolder/someFile.zip.

How do I set download links to files inside someFolder? I often stumbled over "Media Views" I tried implementing them but so far I've been unsuccessful.

Besides is there no easier way to make files downloadable?

  • 写回答

1条回答 默认 最新

  • doubei5310 2013-04-08 20:56
    关注

    Media Views is deprecated since version 2.3. You should use Sending files instead.

    Check out this minimal example in your 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;
    }
    

    The first parameter of $this->response->file is relative to your APP directory. So calling $this->response->file('someFolder' . DS . 'someFile.zip') will download the file APP/someFolder/someFile.zip.

    “Sending files” requires at least CakePHP version 2.0. Please also consider taking a look at the Cookbook link above.


    If you are running an older version of CakePHP you should use Media Views as you already mentioned in your question. Use this code and refer to Media Views (Cookbook).

    Here's the same method for older versions:

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?