yii2用于文件上传的REST api

时间:2017-10-09 09:15:39

标签: php rest file-upload yii2 yii2-advanced-app

我尝试从移动应用上传文件图像/文件类型,并将该图像存储在后端。我使用Yii2框架API来做到这一点。我正在使用邮递员来检查API。我在行动中运行以下内容。

/*Uploading documents*/ 
      public function actionUploading_doc() {  

         $uploads = \yii\web\UploadedFile::getInstanceByName('upfile');

         print_r($uploads);exit;

          if (empty($uploads)){
              return "Must upload at least 1 file in upfile form-data POST";
          } 

          foreach ($uploads as $file){
              $filename = time() . $image->name;
              $path = "uploads/" . $filename;
              $file->saveAs($path);  
          }
       }

当我从邮递员那里以POST方式运行它时,打印$ uploads的值,即获得空值。这意味着它不会进入控制器。 请帮我解决这个问题。

3 个答案:

答案 0 :(得分:0)

对我来说,这就是我没有上传文件类

所做的
  /*Uploading documents*/ 
      public function actionUploading() {  

         $uploads = \yii\web\UploadedFile::getInstanceByName('upfile');

         \yii::$app->request->enableCsrfValidation = false;
          $filename = $uploads->name;
          $path = "http://localhost/projects/YiiRestful/api/web/uploads/".$filename;
          $putdata = fopen("php://input", "r");
           // make sure that you have /web/upload directory (writeable) 
           // for this to work
           $path = "uploads/".$filename;

           $fp = fopen($path, "w");

           while ($data = fread($putdata, 1024))
              fwrite($fp, $data);

           /* Close the streams */
           fclose($fp);
           fclose($putdata);
     }

答案 1 :(得分:0)

我会尝试这样的事情......(未经测试)

public function actionUploadingDoc() {  // good practice to use camel case for methods
    $uploads = \yii\web\UploadedFile::getInstances('upfile');
    if (empty($uploads)){
        return false;
        // handle error reporting somewhere else
    } 
    $path = 'uploads/'; // set your path
    foreach ($uploads as $upload){
        $filename = $path . time() .'_'. $upload->name ;
        $upload->saveAs($filename);  
    }
    return true;
}

答案 2 :(得分:0)

您可以使用base64字符串进行上传。像这样在控制器中定义函数

rawurlencode($imglink)

并使用内部动作

public function base64_to_jpeg($base64_string, $output_file) {
    $path="your/real/path/";
    // open the output file for writing
    $ifp = fopen( $path.$output_file, 'wb' ); 

    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    $data = explode( ',', $base64_string );
    if(count($data)>1) {
        $dataText=$data[ 1 ];
    } else {
        $dataText=$base64_string;
    }

    // we could add validation here with ensuring count( $data ) > 1
    fwrite( $ifp, base64_decode( $dataText ) );

    // clean up the file resource
    fclose( $ifp ); 

    return $output_file; 
}