Post Upload Image

Hi guys, I have a post rest api for creating users. Now my problem is how can I add upload images/files to my post rest api (for profile pictures/more photos) and I want it in form-data… Any suggestions? Thanks

One way is to for the the client to send the image data in a JSON payload, base64 encoded.

can you give me examples or any tutorial sites for this situation?

@anicacute09
There are several ways for doing this.

If you’re using RESTful API, a very good solution is to define an API endpoint for file upload (images in your case).

So you POST to https://api.site.com/media a base64 encoded image, you save it and return the ID that you’ll associate to the user the ID of the stored media.

This is a static function to upload base64 data payload

public static function uploadFromData($data, $storage, $folder = '/') {
    $ext = null;
    
    if(strpos($data, 'data:image/jpeg;base64,') === 0) {
        $data = str_replace('data:image/jpeg;base64,', '', $data);
        $ext = '.jpg';
    } elseif (strpos($data, 'data:image/jpg;base64,') === 0) {
        $data = str_replace('data:image/jpg;base64,', '', $data);
        $ext = '.jpg';
    } elseif (strpos($data, 'data:image/png;base64,') === 0) {
        $data = str_replace('data:image/png;base64,', '', $data);
        $ext = '.png';
    } elseif (strpos($data, 'data:image/gif;base64,') === 0) {
        $data = str_replace('data:image/gif;base64,', '', $data);
        $ext = '.gif';
    }

    if($ext != null) {
        $image = base64_decode($data);

        $filename = date('YmdHis') . '.' . Utils::createToken() . $ext;
        if(file_put_contents($storage . $folder . $filename, $image) !== FALSE) {
            return $filename;
        }
    }
    
    return null;
}

And this is a function to create a token for the other funtion above

public static function createToken() {
    return bin2hex(openssl_random_pseudo_bytes(16));
}

@diegoluisr
i think he is doing the upload from a browser.

you must convert the image in a base64 string from browser or mobile application

Follow this instructions

i am using ionic framework for my mobile app… I already have an api for the data/info but my problem is the uploading of images(profile photo and more photos). I already convert my images to base64… Now I want to upload it in my server database…

@anicacute09
It’s a simple request.
Handle the base64 string just as a input type content.

$http
    .post('http://endpoint.here/media', {'image_content' : 'base64String'})
    .then(function(data) {
        // do stuff here
});