我的目标
我想将一个sqlite文件上传到Google驱动器。
尽管我已经能够将文件上传到google驱动器,但是文件上传名称为“无标题” 。我在Qt的Performing Multipart Upload的帮助下尝试了QHttpMultiPart。
这是我的代码
bool File_Control::Upload_File_Multipart(const QString &FileName, const QByteArray &rawData)
{
if(FileName.isEmpty()){
emit setMessage("Error: File Name can not be empty");
return false;
}
if(rawData.size()==0){
emit setMessage("Error: File size can not be zero");
return false;
}
// Prepare MetaDataPart
QHttpPart MetadataPart;
MetadataPart.setRawHeader("Content-Type", "application/json; charset=UTF-8");
QString Body;
Body = "{\n"
+ tr("\"name\": \"%1\"\n").arg(FileName)
+ tr("}");
MetadataPart.setBody(Body.toUtf8());
// Prepare MediaPart
QHttpPart MediaPart;
MediaPart.setRawHeader("Content-Type", "application/octet-stream");
MediaPart.setBody(rawData);
// Now add MetaDataPart and MediaPart together to form multiPart
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::RelatedType);
multiPart->setBoundary("bound1");
multiPart->append(MetadataPart);
multiPart->append(MediaPart);
// Now Prepare the request
QUrl url("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart");
QNetworkRequest request(url);
QString AccessTokenBearer = "Bearer " + mAccess_Token; // mAccess_Token holds the access_token for the session
request.setRawHeader("Content-Type","Content-Type: multipart/related; boundary=bound1");
request.setRawHeader("Authorization", AccessTokenBearer.toUtf8());
// Get Reply and connect it to set Value
QNetworkReply *reply = mQNAM.post(request, multiPart); // mQNAM is QNetworkAccessManager
QObject::connect(reply, SIGNAL(uploadProgress(qint64,qint64)),
this, SIGNAL(setValue(qint64,qint64))); // Update in gui
// Set timeout mechanism while waiting for reply finished
bool stop = false;
QTimer timer;
timer.setSingleShot(true);
QObject::connect(reply, &QNetworkReply::uploadProgress, [&](){
timer.stop();
timer.start(TIMEOUT); // Restart timer every time upload progress
});
QObject::connect(&timer, &QTimer::timeout, [&](){
stop = true;
});
timer.start(TIMEOUT);
// Wait till the response is completed
while(!reply->isFinished()){
QCoreApplication::processEvents();
if(stop){
reply->abort();
}
}
// Check reply
if(reply->error() != QNetworkReply::NoError){
if(reply->error() == QNetworkReply::OperationCanceledError){
emit setMessage("Error: Timeout");
}
else{
emit setMessage("Error: "+reply->errorString());
}
delete reply;
return false;
}
else{
QByteArray rawData = reply->readAll();
qDebug()<<"Size of reply "<<rawData.size();
qDebug()<<"Data "<<rawData;
delete reply;
return true;
}
}
编辑1
Body.utf8日志->“ {\ n \” name \“:\” db_06_08_2018_16_18_11_979.sqlite \“ \ n}”
答案 0 :(得分:0)
我终于找到了错误。准备请求只是错字
之前:
request.setRawHeader("Content-Type","Content-Type: multipart/related; boundary=bound1");
之后:
request.setRawHeader("Content-Type","multipart/related; boundary=bound1");
这解决了问题。