PDA

View Full Version : How to Upload a Image with POST to Amason S3 in Qt5/c++ ??



susi141
26th June 2015, 16:55
Hello, I'm very new at qt, but I need to upload an image to a Amazon S3 server, but I keep getting this error:


Failure "Error downloading https://bucket_name.s3.amazonaws.com/ - server replied: Forbidden"

I check all the credencialas and keys and they are working fine because I was able to upload the image with curl comands. The problem was when I tried to implemt the code on qt5.

So this it's the code I'm ussing:


QEventLoop eventLoop;
QNetworkAccessManager mgr;
QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));

QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

QHttpPart textPart;
textPart.setHeader(QNetworkRequest::ContentDisposi tionHeader, QVariant("form-data; name=\"key\""));
textPart.setBody("c_test/Pantallazo-10.jpg");

QHttpPart textPart1;
textPart1.setHeader(QNetworkRequest::ContentDispos itionHeader, QVariant("form-data; name=\"AWSAccessKeyId\""));
textPart1.setBody("myAccessKeyId");

QHttpPart textPart2;
textPart2.setHeader(QNetworkRequest::ContentDispos itionHeader, QVariant("form-data; name=\"Policy\""));
textPart2.setBody("myPolicy");

QHttpPart textPart3;
textPart3.setHeader(QNetworkRequest::ContentDispos itionHeader, QVariant("form-data; name=\"Signature\""));
textPart3.setBody("mySignature");

QHttpPart imagePart;
imagePart.setHeader(QNetworkRequest::ContentTypeHe ader, QVariant("image/jpeg"));
imagePart.setHeader(QNetworkRequest::ContentDispos itionHeader, QVariant("form-data; name=\"file\""));
QFile *file = new QFile(QDir::homePath() + "Pantallazo-10.jpg");
file->open(QIODevice::ReadOnly);
imagePart.setBodyDevice(file);
file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart

multiPart->append(textPart);
multiPart->append(textPart1);
multiPart->append(textPart2);
multiPart->append(textPart3);
multiPart->append(imagePart);

QUrl url = QUrl(QString("https://bucket_name.s3.amazonaws.com/"));

QNetworkRequest request(url);
QNetworkReply *reply = mgr.post(request, multiPart); // POST
eventLoop.exec(); // blocks stack until "finished()" has been called

if (reply->error() == QNetworkReply::NoError) {
qDebug() << "Success";
} else {
//failure
qDebug() << "Failure" <<reply->errorString();
multiPart->setParent(reply);
delete reply;
}

I really don't know what to do next, I'm pretty stuck on this one.

anda_skoa
26th June 2015, 18:17
Just as a precaution, check that the file was opened successfully.
Your code assumes that homePath() ends in a directory separator character, I am not sure this is always the case.

Also maybe connect to the authenticationRequired() signal and check if the slot is being invoked.

Cheers,
_