PHPSlim + angular-file-upload

时间:2015-07-14 13:50:29

标签: php angularjs slim angular-file-upload

我使用带有PHP Slim Framework构建的服务器端的angular-upload-file。 在我的FileUploader配置中,我只需:

$scope.uploader = new FileUploader({
    url: 'upload/upload.php'
});

然后在我的后端,就像相关的wiki那样:

 if ( !empty( $_FILES ) ) {
    $tempPath = $_FILES[ 'file' ][ 'tmp_name' ];
    $uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $_FILES[ 'file' ][ 'name' ];
    move_uploaded_file( $tempPath, $uploadPath );
    $answer = array( 'answer' => 'File transfer completed' );
    $json = json_encode($answer);
    echo $json;
} else {
    echo 'No files';
}

问题是当我在不使用PHP Slim的情况下放置此代码时它工作正常,但是当我尝试用PHPSlim包装它时,我得到一个GET请求而不是POST:

enter image description here

有这样的代码:

 $scope.uploader = new FileUploader({
    url: 'API/upload/img'
});

进入API:

$app->post('/upload/img', function(){
if ( !empty( $_FILES ) ) {
    $tempPath = $_FILES[ 'file' ][ 'tmp_name' ];
    $uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $_FILES[ 'file' ][ 'name' ];
    move_uploaded_file( $tempPath, $uploadPath );
    $answer = array( 'answer' => 'File transfer completed' );
    $json = json_encode($answer);
    echo $json;
} else {
    echo 'No files';
}

});

我试着找出问题来自哪里,服务器或客户端? 我尝试使用类似的插件ng-file-upload,但我有完全相同的问题,所以我认为它应该是PHPSlim,但我不确定。

我需要使用PHPSlim,因为我使用中间件来处理一些必需的身份验证请求。

提前致谢,

1 个答案:

答案 0 :(得分:0)

首先,您需要为API调用正确的地址:

datnotformeanfill[sapply(datnotformeanfill, function(x) length(unique(x))>1)]

在后端你需要

var uploader = $scope.uploader = new FileUploader({
  url: 'api/path/upload'
});

如果您对消息响应有问题需要格式化,我会以这种方式构建:

 $app->post('/upload', function() {
      if ( !empty( $_FILES ) ) {... 
      }
 })

还为

创建并设置写文件夹权限
    $answer = array(
          'status' => 'success',
          'message' => 'File transfer completed',
        );
...
  echoResponse(200, $answer);
...
    function echoResponse($status_code, $response) {
        global $app;
        $app->status($status_code);
        $app->contentType('application/json');
        echo json_encode($response, JSON_NUMERIC_CHECK);
    }