2017-10-09 138 views
0

我試圖從移動應用程序上傳文件圖像/文件類型,並將該圖像存儲在後端。我使用Yii2框架API來做到這一點。即時通訊使用郵遞員來檢查API。我在我的行動中運行下面的內容。yii2文件上傳的REST 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); 
      } 
     } 

當我運行這個郵政方法從郵遞員..並打印$上傳我的價值獲得空值。這意味着它不會來控制器。 請幫我解決這個問題。

回答

0

對我來說這是我做過什麼,而不UploadFile類

/*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); 
    } 
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; 
} 
0

可以使用的base64字符串uplod。定義函數內部控制器這樣

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; 
} 

並利用內部行動

public function actionUpload(){ 

    $imgName=md5(uniqid()).'.jpg'; 
    $this->base64_to_jpeg($base64_string, $imgName); 
}