using HTTP POST to upload Image

Oct 5, 2015 at 9:02 AM
dredous wrote:
Hi,

I am making an application using the Parse Rest API to upload image into their cloud service. But I'm having difficulty on how to upload the image.
file_stream<unsigned char>::open_istream(L"IAI.png").then([](basic_istream<unsigned char> fileStream)
    {
        http_client client(U("https://api.parse.com/1/classes/Files"));
        http_request request(methods::POST);
        request.headers().add(U("X-Parse-Application-Id"), U(/* OMITTED */));
        request.headers().add(U("X-Parse-REST-API-Key"), U(/* OMITTED */));
        request.headers().set_content_type(U("application/json"));
        json::value obj;
        obj[L"file"] = json::value::object(fileStream);
        request.set_body(obj);
        client.request(request).then([](http_response response)
        {
            if (response.status_code() == status_codes::Created)
            {
                std::wcout << "Succes in Creating new object" << std::endl;
            }
            else
            {
                std::wcout << "Failed in Creating new object" << std::endl;
            }
        })
            .wait();
    });
Is that the correct way to use the input stream? and i got a failed to create status code when uploading the image. Please help.

Thank you so much.
Hi,

First off, I deleted your post because I don't think you meant to share your API keys. I've copied the entire contents above with the keys scrubbed out :).

Now, taking a glance at the parse APIs shows you probably want to use their binary blob storage type (https://parse.com/docs/rest/guide#objects-data-types). We have a base64 encoding function you can use for that (http://microsoft.github.io/cpprestsdk/namespaceutility_1_1conversions.html#ace12b68e8de65058a8c0f26d47a69b60), however you will need your picture data as a vector of chars.

As long as your pictures aren't massive, I honestly recommend using the standard library's file manipulation facilities (do some searches if you haven't done that before). Once you have your data in a vector, you can base64 encode it using the to_base64() function and turn it into a json string object by using web::json::value::string() (http://microsoft.github.io/cpprestsdk/classweb_1_1json_1_1value.html#a1bce82f8e5338a3e8280d7ff7755616b).

You might need some conversions along the way between utf-8 and utf-16; look in the utility::conversions namespace for that.

Good luck!
Marked as answer by dredous on 10/10/2015 at 11:36 PM
Oct 6, 2015 at 6:54 AM
Hi roschuma,

thanks for replying. i haven't tried to convert picture data as a vector of chars, but I'm going to try as you suggest.

And also, I will save the image as a string based value? so when I need to get the image back to my client app, i need to convert that vector of chars back to picture data? Am I getting it correctly?
Oct 6, 2015 at 9:42 PM
Yes, that should work.