Yii 2 RESTful api upload single image

Upload image in Yii 2 REST API

Hey guys, here comes another year and another code snippeton how to upload images via Yii2 REST API.

I have made this extremely easy by commenting the code,in case you get stuck drop a comment 🙂

public function actionSinglefile()
{
 
  \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  //response array
  $response = array();
  //create date string to be used a year
  $ymd = date("Ymd");
  //get the 'image' being send via api
  //Returns an uploaded file according to the given file input name.
  //The name can be a plain string or a string like an array element (e.g. 'Post[imageFile]', or 'Post[0][imageFile]').

  $uploadedFile = UploadedFile::getInstanceByName('image');
  if ($uploadedFile) {
    //get the uploaded file name
    $filename = $uploadedFile->name;
    //pathinfo() returns more info about the $uploadFile
    $pathinfo = pathinfo($uploadedFile);
    //create a new filename to avoid file collission
    $filename = $pathinfo['filename'].date('YmdHis').rand(10000,99999);
    //get extension
    $extension  = $uploadedFile->getExtension();
    //directory to save the image
    $save_path = \Yii::getAlias('@backend') . '/web/uploads/' . $ymd . '/';
    //check if dir already exists 
      if (!file_exists($save_path)) {
        //make dir ,give permissions
          mkdir($save_path, 0777, true);
        }
        //save file
      $uploadedFile->saveAs($save_path . $filename. '.' . $extension);
    return $response = array(
                              'fileinfo' => pathinfo($uploadedFile),
                              'filename' => $filename
                            );
  } else {
    return array(
                  'file' => $uploadedFile->error,
                );
  }

  
}

 

Yii REST API Guide

How to delete blank empty lines from your code

I will keep this short because again we devs like straight,brief and clear  instructions.

Assume you have such kind of code and you want to remove all these empty lines .How will you go about it?

<?php

// Heading

$_['heading_title']    = 'My Downloads';

$_['heading_title1']    = 'Add Download';



// Text

$_['text_success']     = 'Success: You have modified downloads!';

$_['text_upload']      = 'Your file was successfully uploaded!';

$_['text_loading']      = 'Loading..';



$_['text_edit']      = 'Edit';



$_['text_no_results']      = 'No Results Found';



// Column

$_['column_name']      = 'Download Name';

$_['column_remaining'] = 'Total Downloads Allowed';

$_['column_action']    = 'Action';



$_['column_date_added'] = 'Date Added';


 

Easy! us regular expressions.

Use^\n to be precise.

In your IDE use Find using Regular expressions and Replace.

Example

Find: ^\n

Replace with: (nothing,blank)
So the results of my code will be.

<?php
// Heading
$_['heading_title']    = 'My Downloads';
$_['heading_title1']    = 'Add Download';
// Text
$_['text_success']     = 'Success: You have modified downloads!';
$_['text_upload']      = 'Your file was successfully uploaded!';
$_['text_loading']      = 'Loading..';
$_['text_edit']      = 'Edit';
$_['text_no_results']      = 'No Results Found';
// Column
$_['column_name']      = 'Download Name';
$_['column_remaining'] = 'Total Downloads Allowed';
$_['column_action']    = 'Action';
$_['column_date_added'] = 'Date Added';

Looks good 🙂

In case you have spaces in the line then you can use ^[\s]*?[\n\r]+

May you are wondering what all these regex thing is,have a look look at PHP Regex cheat sheet.

Cheat Sheet

[abc] A single character of: a, b or c
[^abc] Any single character except: a, b, or c
[a-z] Any single character in the range a-z
[a-zA-Z] Any single character in the range a-z or A-Z
^ Start of line
$ End of line
\A Start of string
\z End of string
. Any single character
\s Any whitespace character
\S Any non-whitespace character
\d Any digit
\D Any non-digit
\w Any word character (letter, number, underscore)
\W Any non-word character
\b Any word boundary
(...) Capture everything enclosed
(a|b) a or b
a? Zero or one of a
a* Zero or more of a
a+ One or more of a
a{3} Exactly 3 of a
a{3,} 3 or more of a
a{3,6} Between 3 and 6 of a

Options

i case insensitive  m treat as multi-line string  s dot matches newline  x ignore whitespace in regex  A matches only at the start of string  D matches only at the end of string  U non-greedy matching by default

You have other great ways of doing this? let us know!

Donwload OpenCart 3x MultiVendor Extension

OpenCart 3X Advanced MultiSeller

Features of Multiseller

With MultiSeller you can turn your OpenCart store into a marketplace.
Customers can apply to become sellers on your store(s).

1. Register / Login seller account from frontend .
2. Start uploading category , products, options from seller panel
3. Different images folder for each seller.
4. Seller can change status of order.
6. Seller profile page where customer can see products by vendor.
7. Seller payment options bank transfer,paypal and check.
8. Physical and downloadable product option for seller
9. Seller membership application needs approval from the main admin.
10. After creating products,categories it will go to admin for approval.
11. Admin also can login into seller account from backend using login seller link.
12. Admin can add/assign product to seller from backend.
13. Check seller’s transaction, products against that transactions and the customers
14. Seller Membership Plans
15. Customers can review sellers.
16. Customers can update their profile,show their social media accounts.
17. Subscription system which helps you give different sellers different subscriptions.
18. Free installation if needed.
19. Different seller dashboard.
20. Custom settings in the back end for further customization.20. Custom settings in the back end for further customization.

21.Import products in Bulk

22.Admin approve Sellers.

23.Bootstrap user interface for sellers

24.OpenCart 3x ready

Compatible with major themes.

Demo

Admin:

username: multivendor password:demo

Seller

email:multivendor@demo.com password:demo

Customer

email: multivendor@demo.com password:demo

Download the MultiVendor for FREE

Support Email : info@ovicko.com

Screen shots