How upload image?

Hi,

Uploading file/image(s) with API … how to?

I tried PostMan addon for Chrome, the form-data type returns nothing with PUT !

Thanks

Use Formdata for upload a file from view. and add the following header in your ajax




headers: {'Content-Type': undefined }



Did not work!

There is no tutorial or example to upload file with PUT or POST with API as no one need this option at all !!

You can upload the image by using the UploadedFile::getInstance($model, ‘{attribute}’) in your particular actions.

Example:

$model = new {modelClassName};

if ($model->load ( Yii::$app->request->post () )) {

		$image = UploadedFile::getInstance ( $model, '{attribute}' );


                    $image->saveAs ( YOUR UPLOAD PATH . $image->name );


                    $model->{attribute} = $image->name;


		if ($model->save ()) {


			$response ['status'] = 'OK';


		} else {


			$response ['error'] = $model->errors;


		}


	} else {


		$response ['error'] = 'No Data Posted';


	}

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;

    }

}

How test it with PostMaster chrome add-on?

Anyone?

Body -> form-data -> Select File from the dropdown on the right

This fine, I noticed this, but how to fetch and store the image via API, and the post using json to post another information, both will not work.

You can post image from frontend in base64, and decode it in Yii2 rest controller. But in most cases there is no reason for such a complicated decision.

It’s easer to post file and other data in multipart/form-data format.

I finished most of the project, yet the image upload not solved!

In the PostMaster "form-data" put type, am getting the image information, but it not saved in the folder, here my code.




public function beforeSave($insert) {

		if (parent::beforeSave ( $insert )) {

			$file = \yii\web\UploadedFile::getInstanceByName ( 'car_image' );

			

			if ($file) {

				$this->name = time () . "_x" . uniqid () . '.' . $file->extension;

                                //in params-local    Yii::setAlias ( '@uploadDir', realpath ( dirname ( __FILE__ ) . '/../../car_images' ) );

				$imageDir = Yii::getAlias ( '@uploadDir' ); 

				$file->saveAs ( $imageDir . '/' . $this->name );

				

			}

			return true;

		} else {

			return false;

		}

	}



The strange thing that Yii is really great to build rest app, but missing some information, as if it secret, no one would disclose it.

I got the code … working fine now, here it is if someone need it:




	public function actionCreate() {

		$model = new Pictures ();

		$model->load ( \Yii::$app->getRequest ()->getBodyParams (), '' );

		$image = \yii\web\UploadedFile::getInstanceByName ( ‘imageFile’ );

		

		if (is_object ( $image )) { // if there is image

			$model->name = time () . "_" . uniqid () . '.' . $image->extension;

			$imageDir = \Yii::getAlias ( '@uploadDir' );

			$image->saveAs ( $imageDir . '/' . $model->name );

			\Yii::info ( 'New image saved, transaction_id: ' . $model->transaction_id, __METHOD__ );

		} else {

			\Yii::info ( 'This is not image object!!', __METHOD__ );

		}

		

		if ($model->save ()) {

			$response = \Yii::$app->getResponse ();

			$response->setStatusCode ( 201 );

		} elseif (! $model->hasErrors ()) {

			$response->setStatusCode ( 500 );

			throw new ServerErrorHttpException ( 'Failed to create the object for unknown reason.' );

		}

		

		return $model;

	}




and in the model add




public $imageFile;