Skip to content

Instantly share code, notes, and snippets.

@appcodr
Created July 11, 2014 19:42
Show Gist options
  • Save appcodr/ff02301b259488a69710 to your computer and use it in GitHub Desktop.
Save appcodr/ff02301b259488a69710 to your computer and use it in GitHub Desktop.
REST API controller code in Yii2 to upload photo/file
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;
}
}
@vaibhavpatil111
Copy link

"Undefined index: data",

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment