使用Cake php和AngularJS创建并下载csv文件

时间:2018-06-20 07:08:46

标签: angularjs cakephp export-to-csv

  public function userExport() {
    $list = array
        (
        "Peter,Griffin,Oslo,Norway",
        "Glenn,Quagmire,Oslo,Norway",
    );
    $file = fopen("php://output", "w");
    foreach ($list as $line) {
        fputcsv($file, explode(',', $line));
    }
    fclose($file);
    header('Content-type: text/csv');
    header('Content-Disposition: attachment; filename= "abc.csv"');
    $this->response->download($file);
    return;

}

当我从我的角度服务呼叫此控制器时,上述控制器应该下载CSV文件。但显示错误

错误:

  

找不到UsersController :: userExport()的视图。

上面的代码是否正确?下面是调用此控制器的角度服务代码

   exportUsers: function (success, failure) {
                    $http({
                        method: 'GET',
                        cache: false,
                        url: 'api/users/userExport'
                    }).success(function (data) {
                        success && success(data);
                    }).error(function (data, status) {
                        failure && failure(data, status);
                    });
                }

1 个答案:

答案 0 :(得分:0)

您将得到错误:找不到UsersController :: userExport()的视图错误,因为相应的.ctp文件在您的Views文件夹中不可用。

要么在“用户”文件夹下创建user_export.ctp文件,要么在userExport函数中添加以下行。

<?php
 namespace app\models;

 use Yii;
 use yii\base\Model;

 class LoginForm extends Model
 {
   public $username;
   public $password;
   public $rememberMe = true;

   private $_user = false;

   public function rules()
   {
      return [
        // username and password are both required
        [['username', 'password'], 'required'],
        // rememberMe must be a boolean value
        ['rememberMe', 'boolean'],
        // password is validated by validatePassword()
        ['password', 'validatePassword'],
      ];
    }

    public function validatePassword($attribute, $params)
    {
       if (!$this->hasErrors()) {
          $user = $this->getUser();

          if (!$user || !$user->validatePassword($this->password)) {
              $this->addError($attribute, 'Incorrect username or password.');
          }
       }
     }

     public function login()
     {
         if ($this->validate()) {
            if(!empty($this->getUser()['phone_number'])) {
                return Yii::$app->admin->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
            } else {
                return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
            }
         }
         return false;
      }

      public function getUser()
      {
         if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username);

            if(!$this->_user) {
                $this->_user = Admin::findByUsername($this->username);
             }
          }

          return $this->_user;
       }
    }