I'm trying to make a function that uploads a picture to imgur and the function is working in the form below but differently then I was expecting.
bool ImgurUploader::upload( QImage image )
{
QByteArray byteArray;
QBuffer buffer(&byteArray);
image.save(&buffer, "PNG");
QByteArray params;
params.append(byteArray.toBase64());
QNetworkRequest request;
request.setUrl(QUrl("https://api.imgur.com/3/image"));
request.setRawHeader("Content-Type", "application/application/x-www-form-urlencoded");
request.setRawHeader("Authorization", "Client-ID 16d41e28a3ba71e");
mAccessManager->post(request, params);
}
I was expecting and trying at first to pass the image param in form like this:
params.append("image=");
params.append(byteArray.toBase64());
But when I do I get an "400 Bad Request" and the error is "Invalid URL".
How can I send several params? Am I using the wrong approach?
You can have a look at their Android Upload Example.
If you look at the upload request here, you can see that parameters are not sent in the body of the POST request (as you are trying to do). Instead, they are queries that are appended to the URL (this can be done in Qt using QUrlQuery
), the image is sent in the body of the request and there is no need to encode it using base64 (this is better as it can save some network traffic).
Here is how your upload function should look like:
bool ImgurUploader::upload(QImage image, QString title, QString description)
{
QByteArray byteArray;
QBuffer buffer(&byteArray);
image.save(&buffer, "PNG");
QUrlQuery urlQuery;
urlQuery.addQueryItem("title", title);
urlQuery.addQueryItem("description", description);
QNetworkRequest request;
QUrl url("https://api.imgur.com/3/image");
url.setQuery(urlQuery);
request.setUrl(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,
"application/application/x-www-form-urlencoded");
request.setRawHeader("Authorization", "Client-ID 16d41e28a3ba71e");
mAccessManager->post(request, byteArray);
}