How upload image?


#1

Hi,

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

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

Thanks


(Ilaiyamdu) #2

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




headers: {'Content-Type': undefined }




#3

Did not work!


#4

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


(Shivcharan Panjeta) #5

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


	}

(Jojimltm) #6

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;

    }

}


#7

How test it with PostMaster chrome add-on?


#8

Anyone?


(Kuehn Marcel) #9

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


#10

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.


(Mzimin) #11

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.


#12

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.


#13

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;