-
-
Save aoopvn/592aa006b3e183ee1f97 to your computer and use it in GitHub Desktop.
REST API controller code in Yii2 to upload photo/file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UploadController extends ActiveController | |
{ | |
public $documentPath = 'documents/'; | |
public function verbs() | |
{ | |
$verbs = parent::verbs(); | |
$verbs[ "upload" ] = ['POST' ]; | |
return $verbs; | |
} | |
public function actionUpload() | |
{ | |
$postdata = fopen( $_FILES[ 'data' ][ 'tmp_name' ], "r" ); | |
/* Get file extension */ | |
$extension = substr( $_FILES[ 'data' ][ 'name' ], strrpos( $_FILES[ 'data' ][ 'name' ], '.' ) ); | |
/* Generate unique name */ | |
$filename = $this->documentPath . uniqid() . $extension; | |
/* Open a file for writing */ | |
$fp = fopen( $filename, "w" ); | |
/* Read the data 1 KB at a time | |
and write to the file */ | |
while( $data = fread( $postdata, 1024 ) ) | |
fwrite( $fp, $data ); | |
/* Close the streams */ | |
fclose( $fp ); | |
fclose( $postdata ); | |
/* the result object that is sent to client*/ | |
$result = new UploadResult; | |
$result->filename = $filename; | |
$result->document = $_FILES[ 'data' ][ 'name' ]; | |
$result->create_time = date( "Y-m-d H:i:s" ); | |
return $result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment